wpfjson.net

How to get first key from JObject?


I am using Newtonsoft.Json in my project. I have JObject like this:

{
    "4781":"Name 1",
    "1577":"Name 2",
    "9973":"Name 3"
}

I successfully parse it with JObject.Parse(). I need to get first key from this JObject ("4781"). How do I get it?


Solution

  • Json.NET doesn't directly provide integer indexed access to the properties of a JObject.

    If you do JObject.Parse(jsonString)[0] you get an ArgumentException with the message

    Accessed JObject values with invalid key value: 0. Object property name expected."

    Demo #1 here.

    I suspect Json.NET was implemented that way because the JSON standard states, "An object is an unordered set of name/value pairs."

    That being said, JObject inherits from JContainer which does explicitly implement IList<JToken>. Thus if you upcast a JObject to IList<JToken> you can access the properties by an integer index corresponding to document order:

    IList<JToken> obj = JObject.Parse(jsonString);
    var firstName = ((JProperty)obj[0]).Name;
    

    Demo fiddle #2 here.

    Alternatively you could use LINQ for a type-safe solution without any casting:

    using System;
    using System.Linq;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    
    var obj = JObject.Parse(jsonString);
    var firstName = obj.Properties().Select(p => p.Name).FirstOrDefault();
    

    Demo fiddle #3 here.