我正在探索.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)
}
}
有任何想法吗?
最佳答案
由于被接受的答案对我没有多大帮助,因为它的典型用途之一是“更好地使用此库!”我想出了答案。
是的,
JsonObject.Parse(myJsonString);
返回一个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);
}
我没有尝试过,如果它的JsonArray也可以工作,但是如果它的JsonArray有用,那么您可能想为i做一个经典的:
for (var i = 0; i < jsonObject.Count; i++)
{
Console.WriteLine("value:" + jsonObject[i]);
}
如果您不知道它是否为数组或对象,则可以在之前进行检查
if (jsonObject.GetType() == typeof JsonObject){
//Iterate like an object
}else if (jsonObject.GetType() == typeof JsonArray){
//iterate like an array
}