首页 \ 问答 \ 无法将当前JSON数组(例如[1,2,3])反序列化为具有复杂和嵌套对象的类型(Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects)

无法将当前JSON数组(例如[1,2,3])反序列化为具有复杂和嵌套对象的类型(Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects)

我正在尝试为复杂的对象构建web api。 为此,我构建了自定义绑定器,从JSON反序列化此对象。

我的客户活页夹看起来像:

var paramType = p_BindingContext.ModelType;

    dynamic updatedParam = Activator.CreateInstance(paramType);

    JsonReader reader = new JTokenReader(JObject.Parse
    (p_ActionContext.Request.Content.ReadAsStringAsync().Result));

    JObject jObject = JObject.Load(reader);

    JsonSerializer serializer = new JsonSerializer();

    serializer.Populate(jObject.CreateReader(), updatedParam);//Here the exception thorws

    p_BindingContext.Model = updatedParam; 

序列化的对象非常复杂:

          public class ModelRegisterUserRequest{

              public ModelUser User { get; set; }

    public CampaignItem CampaignWithChosenProposal { get; set; }

    public string ValidationToken { get; set; }

    public string IVRToken { get; set; }

    public string DealerID { get; set; }

    public string SalePersonID { get; set; }
             }

public class CampaignItem
{

    public List<BannerItem> Banners { get; set; }

    public string Code { get; set; }

    public string CustomerInstruction { get; set; }

    public string InfoLink { get; set; }

    public string LobbySubTitle { get; set; }

    public string LobbyTitle { get; set; }

    public string MoreText { get; set; }

    public uint NumOfColumns { get; set; }

    public uint NumOfRows { get; set; }

    public string OriginString { get; set; }
    public int OriginInt { get; set; }

    public List<ProposalItem> Proposals { get; set; }

    public string RegulationsInfoLink { get; set; }

    public string ServiceType { get; set; }

    public string SubTitle { get; set; }

    public string SWDefault { get; set; }

    public string Title { get; set; }   
}

public partial class ProposalItem
{

    public List<string> EquipmentsCode { get; set; }


    public string FeatureCode { get; set; }


    public string InvalidReason { get; set; }


    public bool IsExistsMoreInfo { get; set; }


    public bool IsValid { get; set; }


    public string LeadCode { get; set; }


    public int ParamCombinationCode { get; set; }


    public string ProductCode { get; set; }


    public string ProductCombinationCode { get; set; }


    public string ProposalCode { get; set; }


    public List<ColumnItem> Columns { get; set; }


    public List<MoreInfoItem> MoreInfoList { get; set; }


    public List<string> PricePlans { get; set; }

    public string ProductName { get; set; }    

}

Json是使用Javascript代码中的JSON.stringify命令创建的,如下所示:

 {
   "ValidationToken": "1cc6cca8-44d5-4042-af37-de6a0d198d17",
  "AppID": "TST",
  "campaignWithChosenProposal": {
    "Banners": [
      {
        "LocationCodeString": "ManagerTab",
        "LocationCodeInt": 256,
        "MediaUrl": "<a href=\"c:\\\">BANNER 10</a>"
      }
    ],
    "Code": "CAMP221",
    "CustomerInstruction": "-1",
    "InfoLink": "http://test.aspx",
    "LobbySubTitle": "",
    "LobbyTitle": "",
    "MoreText": "",
    "NumOfColumns": 0,
    "NumOfRows": 0,
    "OriginString": "INT",
    "OriginInt": 4,
    "Proposals": [
      [
        {
          "EquipmentsCode": [
            "5455"
          ],
          "FeatureCode": "BE5455",
          "InvalidReason": "",
          "IsExistsMoreInfo": true,
          "IsValid": true,
          "LeadCode": "3792956510",
          "ParamCombinationCode": 0,
          "ProductCode": "OANTIVRP2",
          "ProductCombinationCode": "0",
          "ProposalCode": "291600010201C8F83661D5B82FD5F3603967588B7A72",
          "Columns": [
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            }
          ],
          "MoreInfoList": [
            {
              "Content": "3",
              "MoreInfoTypesString": "LicenseFrom",
              "MoreInfoTypesInt": 16
            },
            {
              "Content": "3",
              "MoreInfoTypesString": "LicenseTo",
              "MoreInfoTypesInt": 32
            },
            {
              "Content": "4.3",
              "MoreInfoTypesString": "PricePeriod1",
              "MoreInfoTypesInt": 64
            }
          ],
          "PricePlans": [
            "O2"
          ],
          "ProductName": ""
        }
      ]
    ],
    "RegulationsInfoLink": "http://www.test.aspx",
    "ServiceType": "TST",
    "SubTitle": "",
    "SWDefault": "1",
    "Title": ""
  },
  "User": {
    "CurrentLicenseNumber": 0,
    "CustomerID": "21670106",
    "FirstName": "",
    "LastName": "",
    "RequestedLicenseNumber": "3",
    "SubscriberPhoneNumber": "035448428",
    "IdentityNumber": "058470",
    "Email": "alexanrbe@gmail.com",
    "RegistrationStatus": "NOTREGISTERED"
  },
  "SalePersonID": "3178364",
 }

在例外情况下抛出异常,看起来像:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type WebAPI.Models.Entities.Campaigns.CampaignObjects.ProposalItem' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

我花了几个晚上才解决这个异常,但没有找到任何解决方案此网站上的解决方案也被删除但不支持这样复杂的问题。

https://stackoverflow.com/questions/11126242/using-jsonconvert-deserializeobject-to-deserialize-json-to-ac-sharp-poco-class

无法将当前JSON数组(例如[1,2,3])反序列化为类型

有人遇到了这样的JSON意外行为,可以提供帮助吗?

谢谢


I`m trying to build web api for complex object. For this aim I built the custom binder which deserialize this object from JSON.

My Customer Binder looks like:

var paramType = p_BindingContext.ModelType;

    dynamic updatedParam = Activator.CreateInstance(paramType);

    JsonReader reader = new JTokenReader(JObject.Parse
    (p_ActionContext.Request.Content.ReadAsStringAsync().Result));

    JObject jObject = JObject.Load(reader);

    JsonSerializer serializer = new JsonSerializer();

    serializer.Populate(jObject.CreateReader(), updatedParam);//Here the exception thorws

    p_BindingContext.Model = updatedParam; 

The object to serialize is very comlex:

          public class ModelRegisterUserRequest{

              public ModelUser User { get; set; }

    public CampaignItem CampaignWithChosenProposal { get; set; }

    public string ValidationToken { get; set; }

    public string IVRToken { get; set; }

    public string DealerID { get; set; }

    public string SalePersonID { get; set; }
             }

public class CampaignItem
{

    public List<BannerItem> Banners { get; set; }

    public string Code { get; set; }

    public string CustomerInstruction { get; set; }

    public string InfoLink { get; set; }

    public string LobbySubTitle { get; set; }

    public string LobbyTitle { get; set; }

    public string MoreText { get; set; }

    public uint NumOfColumns { get; set; }

    public uint NumOfRows { get; set; }

    public string OriginString { get; set; }
    public int OriginInt { get; set; }

    public List<ProposalItem> Proposals { get; set; }

    public string RegulationsInfoLink { get; set; }

    public string ServiceType { get; set; }

    public string SubTitle { get; set; }

    public string SWDefault { get; set; }

    public string Title { get; set; }   
}

public partial class ProposalItem
{

    public List<string> EquipmentsCode { get; set; }


    public string FeatureCode { get; set; }


    public string InvalidReason { get; set; }


    public bool IsExistsMoreInfo { get; set; }


    public bool IsValid { get; set; }


    public string LeadCode { get; set; }


    public int ParamCombinationCode { get; set; }


    public string ProductCode { get; set; }


    public string ProductCombinationCode { get; set; }


    public string ProposalCode { get; set; }


    public List<ColumnItem> Columns { get; set; }


    public List<MoreInfoItem> MoreInfoList { get; set; }


    public List<string> PricePlans { get; set; }

    public string ProductName { get; set; }    

}

The Json is created with JSON.stringify command from Javascript code and look like :

 {
   "ValidationToken": "1cc6cca8-44d5-4042-af37-de6a0d198d17",
  "AppID": "TST",
  "campaignWithChosenProposal": {
    "Banners": [
      {
        "LocationCodeString": "ManagerTab",
        "LocationCodeInt": 256,
        "MediaUrl": "<a href=\"c:\\\">BANNER 10</a>"
      }
    ],
    "Code": "CAMP221",
    "CustomerInstruction": "-1",
    "InfoLink": "http://test.aspx",
    "LobbySubTitle": "",
    "LobbyTitle": "",
    "MoreText": "",
    "NumOfColumns": 0,
    "NumOfRows": 0,
    "OriginString": "INT",
    "OriginInt": 4,
    "Proposals": [
      [
        {
          "EquipmentsCode": [
            "5455"
          ],
          "FeatureCode": "BE5455",
          "InvalidReason": "",
          "IsExistsMoreInfo": true,
          "IsValid": true,
          "LeadCode": "3792956510",
          "ParamCombinationCode": 0,
          "ProductCode": "OANTIVRP2",
          "ProductCombinationCode": "0",
          "ProposalCode": "291600010201C8F83661D5B82FD5F3603967588B7A72",
          "Columns": [
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            },
            {
              "Content": ""
            }
          ],
          "MoreInfoList": [
            {
              "Content": "3",
              "MoreInfoTypesString": "LicenseFrom",
              "MoreInfoTypesInt": 16
            },
            {
              "Content": "3",
              "MoreInfoTypesString": "LicenseTo",
              "MoreInfoTypesInt": 32
            },
            {
              "Content": "4.3",
              "MoreInfoTypesString": "PricePeriod1",
              "MoreInfoTypesInt": 64
            }
          ],
          "PricePlans": [
            "O2"
          ],
          "ProductName": ""
        }
      ]
    ],
    "RegulationsInfoLink": "http://www.test.aspx",
    "ServiceType": "TST",
    "SubTitle": "",
    "SWDefault": "1",
    "Title": ""
  },
  "User": {
    "CurrentLicenseNumber": 0,
    "CustomerID": "21670106",
    "FirstName": "",
    "LastName": "",
    "RequestedLicenseNumber": "3",
    "SubscriberPhoneNumber": "035448428",
    "IdentityNumber": "058470",
    "Email": "alexanrbe@gmail.com",
    "RegistrationStatus": "NOTREGISTERED"
  },
  "SalePersonID": "3178364",
 }

The Exception is thrown on serilization row and looks like:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type WebAPI.Models.Entities.Campaigns.CampaignObjects.ProposalItem' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

I spent nights for resolve this exception but did not find any solutions Also the solutions on this site are excisted but not supports such complex problem.

https://stackoverflow.com/questions/11126242/using-jsonconvert-deserializeobject-to-deserialize-json-to-a-c-sharp-poco-class

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

Somebody met such JSON unexpected behaiviour and could help?

Thanks


原文:
更新时间:2022-05-24 20:05

最满意答案

BitArray是紧凑的,并允许您执行按位操作。 从MSDN论坛

BitArray对每个值使用一位,而bool []对每个值使用一个字节。 您可以传递给BitArray构造函数一个bools数组,一个字节数组或一个整数数组。 您还可以传递指定所需长度的整数值和(可选)布尔参数,该参数指定是否应设置各个位。


BitArray is compact and allows you to perform bitwise operations. From the MSDN forum :

A BitArray uses one bit for each value, while a bool[] uses one byte for each value. You can pass to the BitArray constructor either an array of bools, an array of bytes or an array of integers. You can also pass an integer value specifying the desired length and (optionally) a boolean argument that specifies if the individual bits should be set or not.

相关问答

更多
  • 也许你正在寻找System.Numerics命名空间中的BigInteger ? 它看起来像它可以做任何你所要求的。 Perhaps you are looking for BigInteger in the System.Numerics namespace? It certainly looks like it can do whatever you are asking for.
  • 做这种天真的做法有什么问题? BitArray A, B, C; A = /* ... */ // Split A into B & C auto n = A.length; B.length = n/2; foreach (i; 0..n/2) B[i] = A[i]; C.length = n - n/2; foreach (i; n/2..n) C[i-n/2] = A[i]; 我在一个小测试用例上试了一下,对我来说工作得很好。 你的代码不工作的原因是因为数组C的长度为零,所以访 ...
  • BitArray类是在您的情况下用于按位操作的理想类。 如果要执行布尔操作,您可能不想将BitArray转换为bool[]或任何其他类型。 它有效地存储bool值(每个值为1位)并为您提供执行按位操作所需的方法。 BitArray.And(BitArray other) , BitArray.Or(BitArray other) , BitArray.Xor(BitArray other)用于布尔操作, BitArray.Set(int index, bool value) , BitArray.Get(i ...
  • 我认为“a”就是你想要的。 a.fromfile(fh)是一个用fh的内容填充a的方法:它不返回一个bitarray。 >>> import bitarray >>> bits = bitarray.bitarray('0000011111') >>> >>> print bits bitarray('0000011111') >>> >>> with open('somefile.bin', 'wb') as fh: ... bits.tofile(fh) ... >>> a = bitar ...
  • And方法改变(即改变对象)BitArray。 来自BitArray.And返回值的文档 : [返回]当前实例,包含当前BitArray中的元素对指定BitArray中相应元素的按位“与”操作的结果。 请注意,这是当前的实例 。 bit1数组将与bit3数组相同。 因为它们是相同的实例listBox3和listBox4将具有相同的值。 编辑:格式和说明 The And method mutates (i.e. alters the object) the BitArray. From documentati ...
  • 不,没有。 我甚至不确定BitArray的哪部分是通用的,如果有的话。 创建一个扩展方法来获取BitArray并在BitArray使用for循环返回一个 bool[]或 List并不难。 for循环不会涉及装箱,因为您将使用BitArray的索引器,并且 bool[] List也可以在没有装箱的情况下枚举。 示例扩展方法: static List ToList( this BitArray ba ) { List l = new List( ...
  • 查看BitArray.Set方法代码: public void Set(int index, bool value) { if (index < 0 || index >= this.Length) { throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (value) { ...
  • 是的,这将导致很多拳击。 但是,在大多数情况下,我实际上并不希望这会对性能造成太大影响 。 这很烦人,但我怀疑很多现实世界的应用程序花费大量时间装箱/拆箱(或者之后清理箱子,当然这是其他费用)。 在你付出任何努力避免它之前,可能值得检查一下。 您可以相当容易地编写自己的迭代器...特别是如果您不关心“版本”是否发生变化。 例如: public static IEnumerable EnumerateBitArray(BitArray bitArray) { for (int i=0; i ...
  • BitArray是紧凑的,并允许您执行按位操作。 从MSDN论坛 : BitArray对每个值使用一位,而bool []对每个值使用一个字节。 您可以传递给BitArray构造函数一个bools数组,一个字节数组或一个整数数组。 您还可以传递指定所需长度的整数值和(可选)布尔参数,该参数指定是否应设置各个位。 BitArray is compact and allows you to perform bitwise operations. From the MSDN forum : A BitArray u ...
  • 复制BitArray的功能并不是非常困难。 首先,如果您需要少于65位,那么您可以使用long或小。 设置个人位: void Set(ref long ba, int bit) { ba |= 1L << bit; } 要清楚一点: void Clear(ref long ba, int bit) { long mask = 1L << bit; mask = ~mask; ba &= mask; } 要查看是否设置了位: bool IsSet(long ba, int ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)