How to deserialize a JSON array with nested arrays of objects

怎甘沉沦 提交于 2019-12-10 10:31:11

问题


I have a JSON string as follows and want to deserialize it:

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

I have created some classes as follows:

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

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

I am calling this JSON.NET method to deserialize the JSON:

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

But I am getting the error below:

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.

What am I doing wrong?


回答1:


Your JSON represents a List<List<JSONResponse>>, not a List<RootClass>. Try it like this:

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

Fiddle: https://dotnetfiddle.net/geRLdb



来源:https://stackoverflow.com/questions/26476663/how-to-deserialize-a-json-array-with-nested-arrays-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!