本文介绍了通过使用JSON System.Json迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在探索.NET 4.5 System.Json 库的功能,但没有太多的文档,这是相当棘手的,由于对搜索流行JSON 。.NET库



我想知道,基本上,我是怎么通过一些JSON倒是循环,例如:



{人物:{西门:{年龄:25},史蒂夫:{年龄:15}}}



我有我的JSON字符串,我想遍历并显示每个人的年龄



所以,首先我会做:



VAR的JSONObject = JsonObject.Parse(myString的);



但后来我在旁边做什么损失。我很惊讶,解析方法返回一个JsonValue不是一个JSONObject



我想要做的真的是什么:

 的foreach(在jsonObject.Children VAR孩子)
{
如果(child.name ==人物)
{
//另外的foreach循环过的人
//得到他们的名字和年龄,例如。 person.Name和person.Children.Age(LINQ这或东西)

}

}


任何想法


解决方案

使用的以及一些LINQ的

  JSON字符串= @{人物:{西门:{年龄:25},史蒂夫:{年龄:15}}}; 

变种人= JsonConvert.DeserializeObject< JObject>(JSON)人物];

VAR字典= people.Children()
.Cast< JProperty>()
.ToDictionary(P => p.Name,P => p.Value [ 年龄]);


I'm exploring the capabilities of .NET 4.5 System.Json library but there isn't much documentation, and it's quite tricky to search for due to the popular JSON.NET library.

I am wondering basically, how I'd loop through some JSON for example:

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

I have my JSON in a string, and I want to iterate through and display the ages of everyone.

So first I'd do:

var jsonObject = JsonObject.Parse(myString);

but then I'm at a loss of what to do next. I'm surprised that the parse method returns a JsonValue not a JsonObject.

What I want to do really is:

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)

}

}

any ideas?

解决方案

Using Json.Net and some Linq

string json = @"{ ""People"": { ""Simon"" : { Age: 25 }, ""Steve"" : { Age: 15 } } }";

var people =  JsonConvert.DeserializeObject<JObject>(json)["People"];

var dict = people.Children()
                 .Cast<JProperty>()
                 .ToDictionary(p => p.Name, p => p.Value["Age"]);

这篇关于通过使用JSON System.Json迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 12:14