如何使用嵌套对象数组反序列化JSON数组 [英] How to deserialize a JSON array with nested arrays of objects

查看:348
本文介绍了如何使用嵌套对象数组反序列化JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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; }
}

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

I am calling this JSON.NET method to deserialize the 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.

我在做什么错了?

推荐答案

您的JSON表示List<List<JSONResponse>>,而不是List<RootClass>.像这样尝试:

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);

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

这篇关于如何使用嵌套对象数组反序列化JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆