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

我有一些看起来像这样的 JSON

[
{
"MobileSiteContent": {
"Culture": "en_au",
"Key": [
"NameOfKey1"
]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]

我将其解析为 JArray:

var array = JArray.Parse(json);

然后,我在数组上循环:

foreach (var content in array)
{


}

contentJToken

如何检索每个项目的“名称”或“键”?

例如,“ MobileSiteContent”或“ PageContent”

177734 次浏览

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 JObject1. (Of course you can also get the JObject2 if desired, which is another JToken.)

Putting it all together we have:

JArray array = JArray.Parse(json);


foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}

Output:

MobileSiteContent
PageContent

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"];


foreach (JProperty attributeProperty in attributes)
{
var attribute = attributes[attributeProperty.Name];
var my_data = attribute["your desired element"];
}

The simplest way is to look at the path of each item in the JSON object.

For Each token As JToken In json
Dim key= token.Path.Split(".").Last
Next

If the JToken key name is unknown, and you only need the key's Value regardless of name, simply use the JToken.Values() method.

The below sample assumes the JToken value is a primitive type - first value found is extracted.
Solution can be extended to support Array values.

JToken fooToken = sourceData.


int someNum =  fooToken .Values<int?>().First() ?? 0;


int someString =  fooToken .Values<string>().First();

Using Linq we can write something like:

JArray array = JArray.Parse(json);


foreach (JObject content in array.Children<JObject>())
{
List<string> keys = content.Properties().Select(p => p.Name).ToList();
}