Arnold Zahrneinder
Arnold Zahrneinder

Reputation: 5200

Json.Net: Getting keys out of JToken

Is there any way to get the keys out of a JToken object? (that means not JObject and just JToken)

Unlike JObject this type return a collection and so far I have not been able to get the keys but just values in string format.

For example:

var raw = JRaw.Parse(x);
foreach(var i in raw){
    // Get the key of i
    // Get the value of i
}

I need to emphasize that I only and only want to use this approach and do not want to go for a different solution.

Upvotes: 1

Views: 7014

Answers (1)

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

You can iterate over all JProperty elements:

foreach(JProperty prop in raw.OfType<JProperty>())
{
   Console.WriteLine($"{prop.Name} = {prop.Value}");
}  

If you know that all elements are properties then you don't need the OfType thing

Upvotes: 3

Related Questions