在 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
有men
和women
,而men
本身有很多不同的男人身份证.因此,如果我将这个完整的东西作为 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();
}
对于 women 数组也是一样,除了 SelectToken()
路径是 people[1].women
.
Same thing for the women array, except the SelectToken()
path would be people[1].women
.
演示: https://dotnetfiddle.net/7BoiUO
这篇关于如何解析嵌套的 JSON 数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!