Getting the name / key of a JToken with JSON.net
C#Jsonjson.netC# Problem Overview
I have some JSON that looks like this
[ { "MobileSiteContent": { "Culture": "en_au", "Key": [ "NameOfKey1" ]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]
I parse this as a JArray:
var array = JArray.Parse(json);
Then, I loop over the array:
foreach (var content in array)
{
}
content
is a JToken
How can I retrieve the "name" or "key" of each item?
For example, "MobileSiteContent" or "PageContent"
C# Solutions
Solution 1 - C#
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
.)
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
Solution 2 - C#
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"];
}
Solution 3 - C#
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);
}
Solution 4 - C#
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();
Solution 5 - C#
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