Getting the name / key of a JToken with JSON.net(使用 JSON.net 获取 JToken 的名称/密钥)
问题描述
我有一些像这样的 JSON
I have some JSON that looks like this
[
{
"MobileSiteContent": {
"Culture": "en_au",
"Key": [
"NameOfKey1"
]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]
我将其解析为 JArray:
I parse this as a JArray:
var array = JArray.Parse(json);
然后,我循环遍历数组:
Then, I loop over the array:
foreach (var content in array)
{
}
content 是一个 JToken
如何检索每个项目的名称"或密钥"?
How can I retrieve the "name" or "key" of each item?
例如,MobileSiteContent"或PageContent"
For example, "MobileSiteContent" or "PageContent"
推荐答案
JToken 是 JObject, JArray, 的基类>JProperty、JValue 等.您可以使用 Children<T>() 方法获取某个 JToken 的子代的过滤列表类型,例如 JObject.每个 JObject 都有一个 JProperty 对象的集合,可以通过 Properties() 方法访问这些对象.对于每个 JProperty,您可以获得它的 Name.(当然你也可以根据需要获取Value,也就是另一个JToken.)
JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)
综合起来我们有:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
输出:
MobileSiteContent
PageContent
这篇关于使用 JSON.net 获取 JToken 的名称/密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JSON.net 获取 JToken 的名称/密钥
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
