Search for a nested value inside of a JSON.net object in C#(在 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
}
我几乎可以走到那里:
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 对象内的嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中搜索 JSON.net 对象内的嵌套值
基础教程推荐
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
