如何使用嵌套的对象数组反序列化JSON数组

时间:2014-10-20 23:37:31

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

我有一个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.

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的JSON代表List<List<JSONResponse>>,而不是List<RootClass>。试试这样:

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

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

相关问题