How do I parse a JSON object in C# when I don#39;t know the key in advance?(事先不知道密钥的情况下,如何在 C# 中解析 JSON 对象?)
问题描述
我有一些如下所示的 JSON 数据:
I have some JSON data that looks like this:
{
"910719": {
"id": 910719,
"type": "asdf",
"ref_id": 7568
},
"910721": {
"id": 910721,
"type": "asdf",
"ref_id": 7568
},
"910723": {
"id": 910723,
"type": "asdf",
"ref_id": 7568
}
}
如何使用 JSON.net 解析它?我可以先这样做:
How can I parse this using JSON.net? I can first do this:
JObject jFoo = JObject.Parse(data);
我需要能够遍历此列表中的每个对象.我希望能够做这样的事情:
I need to be able to iterate over each object in this list. I would like to be able to do something like this:
foreach (string ref_id in (string)jFoo["ref_id"]) {...}
或
foreach (JToken t in jFoo.Descendants())
{
Console.WriteLine((string)t["ref_id"]);
}
但这当然行不通.如果您在编写代码时知道密钥,那么所有示例都非常有用.当您事先不知道密钥时,它就会崩溃.
but of course that doesn't work. All the examples work great if you know the key while writing your code. It breaks down when you don't know the key in advance.
推荐答案
可行;这可行,但并不优雅.我相信有更好的方法.
It's doable; this works but it's not elegant. I'm sure there's a better way.
var o = JObject.Parse(yourJsonString);
foreach (JToken child in o.Children())
{
foreach (JToken grandChild in child)
{
foreach (JToken grandGrandChild in grandChild)
{
var property = grandGrandChild as JProperty;
if (property != null)
{
Console.WriteLine(property.Name + ":" + property.Value);
}
}
}
}
打印:
id:910719
type:asdf
ref_id:7568
id:910721
type:asdf
ref_id:7568
id:910723
type:asdf
ref_id:7568
这篇关于事先不知道密钥的情况下,如何在 C# 中解析 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:事先不知道密钥的情况下,如何在 C# 中解析 JSON 对象?


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01