wpf 如何从 JObject 获取第一个密钥?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31414718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get first key from JObject?
提问by BArtWell
I am using Newtonsoft.Jsonin my project. I have JObjectlike this:
我Newtonsoft.Json在我的项目中使用。我有JObject这样的:
{
"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?
我成功地解析了它JObject.Parse()。我需要从这个 JObject ("4781") 中获取第一个键。我如何得到它?
回答by dbc
Json.NET doesn't directlyprovide integer indexed access to the properties of a JObject.
Json.NET 不直接提供对JObject.
If you do JObject.Parse(jsonString)[0]you get an ArgumentExceptionwith the message
如果你这样做,JObject.Parse(jsonString)[0]你会收到一条ArgumentException消息
Accessed JObject values with invalid key value: 0. Object property name expected."
使用无效键值访问 JObject 值:0。应为对象属性名称。”
Demo #1 here.
演示 #1在这里。
I suspect Json.NET was implemented that way because the JSON standardstates, "An objectis an unorderedset of name/value pairs."
我怀疑 Json.NET 是以这种方式实现的,因为JSON 标准指出,“对象是一组无序的名称/值对。”
That being said, JObjectinherits from JContainerwhich does explicitlyimplement IList<JToken>. Thus if you upcast a JObjectto IList<JToken>you can access the properties by an integer index corresponding to document order:
话虽如此,JObject继承自JContainerwhich 确实明确实现IList<JToken>. 因此,如果您向上转换 a JObject,IList<JToken>您可以通过对应于文档顺序的整数索引访问属性:
IList<JToken> obj = JObject.Parse(jsonString);
var firstName = ((JProperty)obj[0]).Name;
Demo fiddle #2 here.
演示小提琴 #2在这里。
Alternatively you could use LINQ for a type-safe solution without any casting:
或者,您可以将 LINQ 用于类型安全的解决方案,而无需进行任何强制转换:
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.
演示小提琴 #3在这里。

