JSON.NET 使用 linq 选择数组中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9984337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.NET Selecting items in array with linq
提问by gdp
I need to select some values from a json response. Im using json.net, fine with the simpler stuff, but there doesnt seem to be much documentation/tutorials on anything past that. In the json example below i need to select all the ages:
我需要从 json 响应中选择一些值。我使用 json.net,对简单的东西很好,但似乎没有太多关于过去的文档/教程。在下面的 json 示例中,我需要选择所有年龄段:
{
"teacherHolder": [{
"id": 200000001,
"name": "Mr Test",
"class": "a4",
"students": [{
"id": "100532469",
"name": "ben"
},
{
"id": "100506025",
"name": "bill"
},
{
"id": "100000447",
"name": "bob"
}]
}]
}
}
I have tried this and other variations:
我已经尝试过这个和其他变体:
var stuff = response["teacherHolder"].Children()["students"];
var names = from y in stuff.Children().Values()
select y["name"];
and this:
和这个:
var names= response["teacherHolder"]
.Select(s => (string)s.SelectToken("students[0].name")).ToList();
response is a JObject from a webrequest. I just get back this:
响应是来自网络请求的 JObject。我刚回来:
[{"Key":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]","Value":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]"}]
The results are eventually put into a dictionary.
结果最终被放入字典中。
Any idea how to do this? i know it will be simple, i just havent found the right combination.
知道如何做到这一点吗?我知道这很简单,只是我还没有找到正确的组合。
回答by svick
If you want to get the names of all students of all teachers, you can do it for example like this:
如果你想得到所有老师的所有学生的名字,你可以这样做,例如:
var students = response["teacherHolder"].Children()["students"];
var names = students.Children()["name"];
Or, as another option:
或者,作为另一种选择:
var names = from teacher in response["teacherHolder"]
from student in teacher["students"]
select student["name"];
If you want them as IEnumerable<string>, just add Value<string>()at the end of the select. Or add Values<string>(), if you with the first option.
如果你想要它们IEnumerable<string>,只需Value<string>()在select. 或者添加Values<string>(),如果您使用第一个选项。
But it's usually better to create types for your object model, so that you can work with them as with normal objects and not as some special JSON objects.
但通常最好为您的对象模型创建类型,以便您可以像处理普通对象一样使用它们,而不是像一些特殊的 JSON 对象一样使用它们。
If you have that, you could do something like:
如果你有,你可以做这样的事情:
var names = from teacher in response.TeacherHolder
from student in teacher.Students
select student.Name;

