問題描述
我有一個從服務器返回的 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
}
我幾乎可以走到那里:
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.
推薦答案
我的最終目標是能夠搜索到route3"并回到19007
My ultimate goal is to be able to search for "route3" and get back 19007
您可以使用 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 對象內的嵌套值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!