简体   繁体   English

Newtonsoft JSON 反序列化问题 [将值转换为类型时出错]

[英]Newtonsoft JSON Deserialize Issue [Error converting value to type]

Utilizing C# Newtownsoft JSON libraries... I have run into this issue.使用 C# Newtownsoft JSON 库...我遇到了这个问题。

To set the stage...设置舞台...

I have this JSON from a RESTful Web Service:我有一个来自 RESTful Web 服务的 JSON:

[
    {
        "CorporateArea": "Brampton",
        "ServiceAddress": "321 Heart Lake Road",
        "VendorName": "Enbridge Gas Distribution Inc",
        "MeterNumber": "502105",
        "RateClass": "NG-R6",
        "Department": "22603",
        "Account": "12008",
        "VendorID": "0000001195",
        "MeterLevelID": 2882,
        "SiteAddressID": 468,
        "MappingLocation": "Beckett Sproule",
        "ElectricalBilling": "",
        "EnergyLine": "",
        "CorporateGroup": "Public Works"
    }
]

I also have these C# classes:我也有这些 C# 类:

public class AccountInfo
{
    [JsonProperty("Account")]
    public string Account { get; set; }

    [JsonProperty("CorporateArea")]
    public string CorporateArea { get; set; }

    [JsonProperty("CorporateGroup")]
    public string CorporateGroup { get; set; }

    [JsonProperty("Department")]
    public string Department { get; set; }

    [JsonProperty("ElectricalBilling")]
    public string ElectricalBilling { get; set; }

    [JsonProperty("EnergyLine")]
    public string EnergyLine { get; set; }

    [JsonProperty("MappingLocation")]
    public string MappingLocation { get; set; }

    [JsonProperty("MeterLevelID")]
    public string MeterLevelID { get; set; }

    [JsonProperty("MeterNumber")]
    public string MeterNumber { get; set; }

    [JsonProperty("RateClass")]
    public string RateClass { get; set; }

    [JsonProperty("ServiceAddress")]
    public string ServiceAddress { get; set; }

    [JsonProperty("SiteAddressID")]
    public string SiteAddressID { get; set; }

    [JsonProperty("VendorID")]
    public string VendorID { get; set; }

    [JsonProperty("VendorName")]
    public string VendorName { get; set; }
}

public class JSONArray {
   public IList<AccountInfo> AccountsInfo { get; set; }
}

From these, I call this Newtownsoft Method:从这些,我称之为 Newtownsoft 方法:

JSONArray Accounts = JsonConvert.DeserializeObject<JSONArray> (responseBody,
   new JsonSerializerSettings
   {
      NullValueHandling = NullValueHandling.Ignore
   });

But everytime I do so, I get the exception Newtonsoft.Json.JsonSerializationException with the error message:但是每次我这样做时,都会收到异常 Newtonsoft.Json.JsonSerializationException 和错误消息:

Error converting value "[{"CorporateArea":"Brampton","ServiceAddress":"321 Heart Lake Road","VendorName":"Enbridge Gas Distribution Inc","MeterNumber":"502105","RateClass":"NG-R6","Department":"22603","Account":"12008","VendorID":"0000001195","MeterLevelID":2882,"SiteAddressID":468,"MappingLocation":"Beckett Sproule","ElectricalBilling":"","EnergyLine":"","CorporateGroup":"Public Works"}]" to type 'TestWebService_Consume.JSONArray'.错误转换值 "[{"CorporateArea":"Brampton","ServiceAddress":"321 Heart Lake Road","VendorName":"Enbridge Gas Distribution Inc","MeterNumber":"502105","RateClass":"NG -R6","Department":"22603","Account":"12008","VendorID":"0000001195","MeterLevelID":2882,"SiteAddressID":468,"MappingLocation":"Beckett Sproule"," ElectricalBilling":"","EnergyLine":"","CorporateGroup":"Public Works"}]" 输入“TestWebService_Consume.JSONArray”。 Path '', line 1, position 421.路径 '',第 1 行,位置 421。

I've tried messing with the JSON string so it's not an array, and casting it into a simple AccountsInfo object, it returns the same error.我尝试弄乱 JSON 字符串,使其不是数组,并将其转换为简单的 AccountsInfo 对象,它返回相同的错误。

I must be doing something wrong, but it's been some time since I've worked with the Newtonsoft JSON libraries, so I'm at a loss of what could possible be the issue here.我一定是做错了什么,但是自从我使用 Newtonsoft JSON 库以来已经有一段时间了,所以我不知道这里可能是什么问题。

The Deserialization output for the JSON is when trying with 尝试使用JSON进行反序列化输出

JSONArray Accounts = JsonConvert.DeserializeObject<JSONArray>(json, new JsonSerializerSettings
                           {
                               NullValueHandling = NullValueHandling.Ignore
                           });

is

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'JustSO.JSONArray' because the type requires a JSON object (eg {\\"name\\":\\"value\\"}) to deserialize correctly. 无法将当前JSON数组(例如[1,2,3])反序列化为类型“ JustSO.JSONArray”,因为该类型需要JSON对象(例如{\\“ name \\”:\\“ value \\”})才能正确反序列化。 To fix this error either change the JSON to a JSON object (eg {\\"name\\":\\"value\\"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. 要解决此错误,请将JSON更改为JSON对象(例如{\\“ name \\”:\\“ value \\”}),或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList)例如可以从JSON数组反序列化的List。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 还可以将JsonArrayAttribute添加到类型中,以强制其从JSON数组反序列化。

But if you try like this 但是如果你这样尝试

List<AccountInfo> lc = JsonConvert.DeserializeObject<List<AccountInfo>>(json, new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
});

or 要么

List<AccountInfo> lc = JsonConvert.DeserializeObject<List<AccountInfo>>(json);

will give you the resultant json into Object. 将给您生成的json转换为Object。

附加截图

Your JSOn is not an object, but an array of objects, so you don't need a class to wrap the array, you should deserialize directly to array: 您的JSOn不是一个对象,而是一个对象数组,因此您不需要类来包装该数组,您应该直接将其反序列化为array:

var Accounts = JsonConvert.DeserializeObject<List<AccountInfo>>(responseBody, 
               new JsonSerializerSettings
                {
                   NullValueHandling = NullValueHandling.Ignore
                });

If you really want to have JSONArray object, you could create it and serialize to it's property. 如果您确实想要JSONArray对象,则可以创建它并序列化为它的属性。 Just to mention: your AccountInfo property is private, you should change it to public to deserialize to it. 只需提及:您的AccountInfo属性是私有的,您应该将其更改为public以反序列化它。

JSONArray Accounts = new JSONArray
{
    AccountsInfo = JsonConvert.DeserializeObject<List<AccountInfo>>(responseBody,
           new JsonSerializerSettings
           {
             NullValueHandling = NullValueHandling.Ignore
           })
};

I use Newtonsoft.Json in generic read and write methods for Excel spreadsheets.我在 Excel 电子表格的通用读写方法中使用 Newtonsoft.Json。 Had this exception start throwing, and turned out to be a change made to the excel spreadsheet.如果这个异常开始抛出,结果是对 Excel 电子表格进行了更改。 In general column types, the first cell is used to set the data table type, generally with a header column this ends up being a string.在一般的列类型中,第一个单元格用于设置数据表类型,通常带有一个标题列,它最终是一个字符串。 The excel I was trying to load had a new row added at the top for zero indexing, so all columns were being set as system.double.我试图加载的 excel 在顶部添加了一个新行,用于零索引,因此所有列都被设置为 system.double。

Just thought I'd throw that here, since it took a while to track down why this error started happening after years of working perfectly.只是想我会把它扔在这里,因为花了一段时间来追踪为什么在多年完美工作后开始发生这个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM