无法将当前 JSON 数组(例如 [1,2,3])反序列化为具有复杂和嵌套对象的类型

Posted

技术标签:

【中文标题】无法将当前 JSON 数组(例如 [1,2,3])反序列化为具有复杂和嵌套对象的类型【英文标题】:Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects 【发布时间】:2013-07-20 04:04:30 【问题描述】:

我正在尝试为复杂对象构建 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://***.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

有人遇到了这种 JSON 意外行为并可以提供帮助吗?

谢谢

【问题讨论】:

【参考方案1】:

根据您的 JSON 数据,您需要映射的对象必须如下所示(当然,除非您有自己的 JsonDeserializer):

public class Banner

    public string LocationCodeString  get; set; 
    public int LocationCodeInt  get; set; 
    public string MediaUrl  get; set; 


public class CampaignWithChosenProposal

    public List<Banner> 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 int NumOfColumns  get; set; 
    public int NumOfRows  get; set; 
    public string OriginString  get; set; 
    public int OriginInt  get; set; 
    public List<List<>> 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 class User

    public int CurrentLicenseNumber  get; set; 
    public string CustomerID  get; set; 
    public string FirstName  get; set; 
    public string LastName  get; set; 
    public string RequestedLicenseNumber  get; set; 
    public string SubscriberPhoneNumber  get; set; 
    public string IdentityNumber  get; set; 
    public string Email  get; set; 
    public string RegistrationStatus  get; set; 


public class RootObject

    public string ValidationToken  get; set; 
    public string AppID  get; set; 
    public CampaignWithChosenProposal campaignWithChosenProposal  get; set; 
    public User User  get; set; 
    public string SalePersonID  get; set; 

这是一个非常酷的工具 (json2csharp) 可以帮助您。

【讨论】:

感谢 Dimitar 我在 Json 序列化程序中发现了我的错误 @Dimitar 感谢您提供指向 json2csharp.com 的链接。非常酷的工具。

以上是关于无法将当前 JSON 数组(例如 [1,2,3])反序列化为具有复杂和嵌套对象的类型的主要内容,如果未能解决你的问题,请参考以下文章

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“ConsoleAppTest01.Location”,因为该类型需要 JSON 对象

无法将当前 JSON 数组(例如 [1,2,3])反序列化为具有复杂和嵌套对象的类型

无法将当前 JSON 数组(例如 [1,2,3])反序列化为“System.Collections.Generic.Dictionary”类型

无法将当前 JSON 对象(例如 "name":"value")反序列化为类型“Value[]”,因为该类型需要 JSON 数组(例如 [1,2,3])

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

无法将 JSON 数组(例如 [1,2,3])反序列化为类型 ' ',因为类型需要 JSON 对象(例如 "name":"value")才能正确反序列化