无法将当前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.
我花了几个晚上才解决这个异常,但没有找到任何解决方案此网站上的解决方案也被删除但不支持这样复杂的问题。
有人遇到了这样的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.
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
Somebody met such JSON unexpected behaiviour and could help?
Thanks
原文:
最满意答案
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.
相关问答
更多-
有没有人发布过更强大的BitArray for .NET?(Has anyone released a more robust BitArray for .NET? [closed])[2022-06-06]
也许你正在寻找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(How to split a BitArray)[2024-01-05]
做这种天真的做法有什么问题? 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为零和1(BitArray to zeros and ones)[2023-05-31]
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 ...
-
BitArray与操作(BitArray AND operation)[2022-06-19]
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线程安全(BitArray Thread Safety)[2022-11-21]
查看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 VS布尔[](Bitarray VS bool[])[2023-05-27]
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 ...