JSON.NET使用linq选择数组中的项目 [英] JSON.NET Selecting items in array with linq

查看:98
本文介绍了JSON.NET使用linq选择数组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从json响应中选择一些值.我使用的是json.net,可以使用更简单的内容,但是似乎没有太多的文档/教程.在下面的json示例中,我需要选择所有年龄段:

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"];

和这个:

var names= response["teacherHolder"]
            .Select(s => (string)s.SelectToken("students[0].name")).ToList();

响应是来自Web请求的JObject. 我刚得到这个:

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.

推荐答案

如果要获取所有老师的所有学生的姓名,则可以这样进行:

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"];

如果希望它们作为IEnumerable<string>,只需在select的末尾添加Value<string>().或者,如果您选择第一个选项,则添加Values<string>().

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.

但是通常最好为对象模型创建类型,以便您可以像处理普通对象一样使用它们,而不能像某些特殊的JSON对象那样使用它们.

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;

这篇关于JSON.NET使用linq选择数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆