Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first key from JObject?

Tags:

wpf

json.net

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?

like image 460
BArtWell Avatar asked Jul 14 '15 18:07

BArtWell


People also ask

How do you find the first value of a JSON object?

The Object. values() will return an only array of values available in an object, now we can easily get the first value from the JSON object using array 0th index.

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...


1 Answers

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.

like image 148
dbc Avatar answered Oct 09 '22 09:10

dbc