JSON.NET Selecting items in array with linq

a 夏天 提交于 2019-12-10 02:06:36

问题


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:

{
"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:

[{"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.


回答1:


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.

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.

If you have that, you could do something like:

var names = from teacher in response.TeacherHolder
            from student in teacher.Students
            select student.Name;


来源:https://stackoverflow.com/questions/9984337/json-net-selecting-items-in-array-with-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!