使用System.Json遍历JSON

Nib*_*Pig 3 c# json .net-4.5

我正在探索.NET 4.5 System.Json库的功能,但是没有太多文档,而且由于流行的JSON.NET库,搜索起来非常棘手。

我基本上想知道,例如,如何遍历一些JSON:

{ "People": { "Simon" : { Age: 25 }, "Steve" : { Age: 15 } } }

我的字符串中包含JSON,我想遍历并显示每个人的年龄。

所以首先我要做:

var jsonObject = JsonObject.Parse(myString);

但是后来我不知所措。我很惊讶parse方法返回JsonValue而不是JsonObject。

我真正想做的是:

foreach (var child in jsonObject.Children)
{
  if (child.name == "People")
{
 // another foreach to loop over the people
 // get their name and age, eg. person.Name and person.Children.Age (LINQ this or something)

}

}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 6

由于被接受的答案对我没有多大帮助,因为它的典型用途之一是“更好地使用此库!” 答案我知道了。

是,

JsonObject.Parse(myJsonString);
Run Code Online (Sandbox Code Playgroud)

返回一个JsonValue对象,该对象是System.Json中所有Json *类的基类。当您调用JsonObject.Parse(..)时,实际上会因为继承而调用JsonValue.Parse()。

要遍历JsonObject,可以使用:

var jsonObject = JsonValue.parse(jsonString);

foreach (KeyValuePair<string, JsonValue> value in jsonObject)
{
    Console.WriteLine("key:" + value.Key);
    Console.WriteLine("value:" + value.Value);
}
Run Code Online (Sandbox Code Playgroud)

我没有尝试过如果它也可以使用JsonArray,但如果它也可以使用,那么您可能想用i的经典方法来做:

for (var i = 0; i < jsonObject.Count; i++)
{
    Console.WriteLine("value:" + jsonObject[i]);
}
Run Code Online (Sandbox Code Playgroud)

如果您不知道它是数组还是对象,则可以在之前检查一下

if (jsonObject.GetType() == typeof JsonObject){
    //Iterate like an object 
}else if (jsonObject.GetType() == typeof JsonArray){
    //iterate like an array
}
Run Code Online (Sandbox Code Playgroud)