Nick
Nick

Reputation: 471

How to get JObject's root name

I cannot believe this is such difficult, but found no simple solution!

I have a JObject representing a JSON like

"MyData1": {
  "Data": "foo"
}

I need the root item's name (=Key) in the JObject, but don't like to iterate like it's proposed in other answers like this:

var jsonObject = JObject.Parse(jsonString);
foreach (var tmp in jsonObject) 
{
    Console.WriteLine(tmp.Key);
}

This foreach construct gives me a KeyValuePair, which has the Key property. How can I get this just for the very first item in my JObject?

(The only workaround I found is using a System.Xml.Linq.XDocument instead of JObject - this provides a Root.Name property.)

Upvotes: 0

Views: 1017

Answers (1)

Vivek Nuna
Vivek Nuna

Reputation: 1

Use the below code to get the first key, please make sure your object is not null and has at least one item

((JProperty)jsonObject[0]).Name 

Upvotes: 2

Related Questions