如何解析嵌套的JSON数据结构 [英] How to parse nested JSON data structure

查看:269
本文介绍了如何解析嵌套的JSON数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows Phone应用中,我需要解析JSON数据.我能够获取未嵌套的键的值.但是,如果JSON在数组中包含数组,那么如何从JSON文件中提取值?

In a Windows Phone app I need to parse JSON data. I am able to get the values for keys which aren't nested. But if the JSON has arrays inside arrays, then how do I extract values from the JSON file?

过去,我所做的工作是将JSON解析为JArray对象,然后从JToken中获得指定字符串键的值.

In the past what I did was parse the JSON into a JArray object, then from the JToken I got the value of a specified string key.

在下面的JSON中,people具有menwomen,并且men本身具有许多具有不同ID的人.因此,如果我将这个完整的东西作为JSON字符串使用,该如何打印特定男人的ID值?如果这里没有嵌套数组,我本可以转换为JArray并访问索引值,但是现在该怎么办?

In the JSON below, people has men and women, and men itself has many men with different IDs. So if I have this complete thing as a JSON string, how do I print the value of the ID of a particular man? I could have converted into JArray and access indexed values if there were no nested arrays here, but how to do it now?

这是我的JSON:

{
    "people": [
        {
            "men": [
                {
                    "id": 0,
                    "name": "alex",
                    "age": 25
                },
                {
                    "id": 1,
                    "name": "bob",
                    "age": 26
                },
                {
                    "id": 2,
                    "name": "charlie",
                    "age": 27
                }
            ]
        },
        {
            "women": [
                {
                    "id": 0,
                    "name": "alexys",
                    "age": 25
                },
                {
                    "id": 1,
                    "name": "bethany",
                    "age": 26
                },
                {
                    "id": 2,
                    "name": "catherine",
                    "age": 27
                }
            ]
        }
    ]
}

推荐答案

在顶级JToken中,您可以使用SelectToken()导航到具有您感兴趣的数据的JArray:

From the top-level JToken, you can use SelectToken() to navigate to the JArray that has the data you are interested in:

JToken token = JToken.Parse(json);
JArray men = (JArray)token.SelectToken("people[0].men");

从那里您可以像通常那样处理JArray:

From there you can process the JArray as you normally would:

foreach (JToken m in men)
{
    Console.WriteLine("id: " + m["id"]);
    Console.WriteLine("name: " + m["name"]);
    Console.WriteLine("age: " + m["age"]);
    Console.WriteLine();
}

与女人数组相同,除了SelectToken()路径为people[1].women.

Same thing for the women array, except the SelectToken() path would be people[1].women.

演示: https://dotnetfiddle.net/7BoiUO

这篇关于如何解析嵌套的JSON数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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