使用 JSON.net 获取 JToken 的名称/密钥

Getting the name / key of a JToken with JSON.net(使用 JSON.net 获取 JToken 的名称/密钥)
本文介绍了使用 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"

推荐答案

JTokenJObject, JArray, 的基类>JPropertyJValue 等.您可以使用 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 的名称/密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)