How to get first key from JObject?

强颜欢笑 提交于 2019-12-07 02:30:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31414718/how-to-get-first-key-from-jobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!