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 对象内的嵌套值
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01