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 的名称/密钥
				
        
 
            
        - C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
 - 在 C# 中异步处理项目队列 2022-01-01
 - 在 LINQ to SQL 中使用 contains() 2022-01-01
 - 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
 - Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
 - 使用 rss + c# 2022-01-01
 - CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
 - 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
 - 带问号的 nvarchar 列结果 2022-01-01
 - Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
 
						
						
						
						
						