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?
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.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With