【问题标题】:How to deserialize a JSON array with nested arrays of objects如何反序列化带有嵌套对象数组的 JSON 数组
【发布时间】:2014-10-20 23:37:31
【问题描述】:

我有一个如下的 JSON 字符串,想反序列化它:

[[{"campaignId":201410018,"programCode":"54321"}],[{"campaignId":201410018,"programCode":"54321"}]]

我创建了一些类如下:

public class Rootclass
{
    public List<JSONResponse> rootClass { get; set; }
}

public class JSONResponse
{
    public int campaignId { get; set; }
    public string programCode { get; set; }
}

我正在调用这个 JSON.NET 方法来反序列化 JSON:

List<Rootclass> myDeserializedObjList = (List<Rootclass>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Rootclass>));

但我收到以下错误:

Cannot deserialize JSON array (i.e. [1,2,3]) into type 'JSON_Test.Rootclass'.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.

我做错了什么?

【问题讨论】:

    标签: c# .net json json.net deserialization


    【解决方案1】:

    您的 JSON 代表 List&lt;List&lt;JSONResponse&gt;&gt;,而不是 List&lt;RootClass&gt;。试试这样:

    List<List<JSONResponse>> myDeserializedObjList = 
        JsonConvert.DeserializeObject<List<List<JSONResponse>>>(json);
    

    小提琴:https://dotnetfiddle.net/geRLdb

    【讨论】:

    • 如何反序列化低于 JSON 字符串。 string json = @"[[{""campaignId"":201410018,""programCode"":""54321""},{""reason"":201410018,""about"":""54321""} ],[{""campaignId"":201410019,""programCode"":""54322""},{""reason"":201410018,""about"":""54321""}]]";
    • 有几种可能的解决方案。快速而简单的方法是将reasonabout 属性添加到您的JSONResponse 对象中。见fiddle here。如果您想为包含campaignIdreason 的对象设置单独的类,那么您将需要使用JsonConverter。第三种可能性是反序列化为dynamicJToken,而不是使用强类型类。
    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    相关资源
    最近更新 更多