使用JSON.NET解析嵌套的JSON对象

13

我的JSON数据源具有类似于这样的嵌套对象:

{
"id": 1765116,
"name": "StrozeR",
"birth": "2009-08-12",
"avatar": "http:\/\/static.erepublik.com\/uploads\/avatars\/Citizens\/2009\/08\/12\/f19db99e9baddad73981d214a6e576ef_100x100.jpg",
"online": true,
"alive": true,
"ban": null,
"level": 61,
"experience": 183920,
"strength": 25779.42,
"rank": {
    "points": 133687587,
    "level": 63,
    "image": "http:\/\/www.erepublik.com\/images\/modules\/ranks\/god_of_war_1.png",
    "name": "God of War*"
},
"elite_citizen": false,
"national_rank": 6,
"residence": {
    "country": {
        "id": 81,
        "name": "Republic of China (Taiwan)",
        "code": "TW"
    },
    "region": {
        "id": 484,
        "name": "Hokkaido"
    }
}
}

我的对象类别像这样:

class Citizen
{
    public class Rank
    {
        public int points { get; set; }
        public int level { get; set; }
        public string image { get; set; }
        public string name { get; set; }
    }
    public class RootObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public string avatar { get; set; }
        public bool online { get; set; }
        public bool alive { get; set; }
        public string ban { get; set; }
        public string birth { get; set; }
        public int level { get; set; }
        public int experience { get; set; }
        public double strength { get; set; }
        public List<Rank> rank { get; set; }

    }
}
我尝试使用以下代码解析我的JSON数据
private async void getJSON()
{
    var http = new HttpClient();
    http.MaxResponseContentBufferSize = Int32.MaxValue;
    var response = await http.GetStringAsync(uri);

    var rootObject = JsonConvert.DeserializeObject<Citizen.RootObject>(response);
    uriTB.Text = rootObject.name;
    responseDebug.Text = response;
}

但是我收到了以下错误:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Erepublik.Citizen+Rank]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

我甚至无法解析主对象中的值。有什么方法可以修复这个问题?如何解析嵌套对象内的值?例如:在“rank”中的“points”


只是想知道你是如何将 residencecountryregion 反序列化为 C# 类的。我也遇到了类似的问题。你能否请发布一下代码? - Venkata Dorisala
1个回答

23
就像错误信息所说,您在.NET类中的rank属性是一个List<Rank>,但在您的JSON中它只是一个嵌套对象,而不是数组。将其改为Rank,而不是List<Rank>
JSON中的数组(或任何JavaScript)都用[]括起来。 {}字符指定单个对象。 CLR类型必须大致匹配JSON类型才能反序列化。 对象到对象,数组到数组。

旧帖子,但今天它帮了我很多。节省时间。 - Hemanth Vanal
那么解决方案是什么?你需要为List<Rank>创建一个包装器吗?有更简洁的解决方案吗? - sky91
不使用包装器,如果您想使用List<Rank>,则JSON需要以Ranks数组的形式呈现。由于JSON中未使用数组,因此只是Rank,而不是List<Rank>。 - DetectivePikachu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接