本文介绍了在C#中的JSON.net对象内搜索嵌套值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从服务器返回的JSON流,我需要使用JSON.net来搜索节点"ID"的特定值以解析数据.而且我几乎可以使它正常工作,但是由于返回的结果彼此之间深深地嵌套在一起,所以不能完全做到这一点-这是由于我重新获得了文件夹结构.我将JSON简化为一个简单得多的版本.我得到这个:

I've got a JSON stream coming back from a server, and I need to search for a specific value of the node "ID" using JSON.net to parse the data.And I can almost make it work, but not quite because the results coming back are deeply nested in each other -- this is due to the fact that I'm getting a folder structure back. I've boiled the JSON down to a much simpler version. I'm getting this:

{
    "data": {
        "id": 0,
        "name": "",
        "childFolders": [{
            "id": 19002,
            "name": "Locker",
            "childFolders": [{
                "id": 19003,
                "name": "Folder1",
                "childFolders": [],
                "childComponents": [{
                    "id": 19005,
                    "name": "route1",
                    "state": "STOPPED",
                    "type": "ROUTE"
                }]
            }, {
                "id": 19004,
                "name": "Folder2",
                "childFolders": [],
                "childComponents": [{
                    "id": 19008,
                    "name": "comm1",
                    "state": "STOPPED",
                    "type": "COMMUNICATION_POINT"
                }, {
                    "id": 19006,
                    "name": "route2",
                    "state": "STOPPED",
                    "type": "ROUTE"
                }, {
                    "id": 19007,
                    "name": "route3",
                    "state": "STOPPED",
                    "type": "ROUTE"
                }]
            }],
            "childComponents": []
        }],
        "childComponents": []
    },
    "error": null
}

我几乎可以通过以下方式到达那里:

I can almost get there by going:

var objects = JObject.Parse(results);
var subobjects = objects["data"]["childFolders"][0]["childFolders"][1];

我可以在调试视图中看到它将解析对象,但不允许我在其中进行搜索.

I can see in the debug view that it'll parse the object, but won't let me search within.

我的最终目标是能够搜索"route3"并获取19007,因为那是该路由的ID.我发现了一些结果,但是所有这些结果都假定您知道对象嵌套的距离.我要搜索的对象可能是2深或20深.

My ultimate goal is to be able to search for "route3" and get back 19007, since that's the ID for that route. I've found some results, but all of them assume you know how far nested the object is. The object I'm searching for could be 2 deep or 20 deep.

推荐答案

您可以使用JObject的 linq Descendants 方法来做到这一点:

You can use linq and Descendants method of JObject to do it:

var dirs = JObject.Parse(json)
            .Descendants()
            .Where(x=>x is JObject)
            .Where(x=>x["id"]!=null && x["name"]!=null)
            .Select(x =>new { ID= (int)x["id"], Name = (string)x["name"] })
            .ToList();

var id = dirs.Find(x => x.Name == "route3").ID;

这篇关于在C#中的JSON.net对象内搜索嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:07