在Json.Net中获取JObject的名称 [英] Get the name of a JObject in Json.Net
问题描述
我的JObject
等于:
"Info":
{
"View":"A",
"Product":"B",
"Offer":"Offer1",
"Demo":"body {background-color:red;} #box {border:dotted 50px red;}",
"Log":false
}
如何返回对象名称"Info"?
How can I return the name of the object, "Info"?
我目前正像这样使用Path
属性:
I am currently using the Path
property like so:
jObject.Name = jObject.Path.Substring(jObject.Path.jObject('.') + 1);
有更好的方法吗?
推荐答案
在JSON中,对象本身没有名称.一个对象只是一个容器,用于存储以大括号开头和结尾的名称/值对.因此,您上面的内容是一个更大的JSON主体的片段.必须有一个外部对象包含它.该外部对象具有名称为Info
的属性,并且该属性的值是您所引用的对象.
In JSON, objects themselves do not have names. An object is just a container for a collection of name-value pairs, beginning and ending with curly braces. So what you have above is a fragment of a larger body of JSON. There must be an outer object to contain it. That outer object has a property with a name of Info
, and the value of that property is the object you are referring to.
{
"Info":
{
"View":"A",
"Product":"B",
"Offer":"Offer1",
"Demo":"body {background-color:red;} #box {border:dotted 50px red;}",
"Log":false
}
}
在Json.Net中,JObject
为JSON对象建模,而JProperty
为JObject
中包含的名称-值对建模.每个JObject
都有一个JProperties
子集,而每个JProperty
都有一个Name
和一个子集Value
.
In Json.Net, a JObject
models a JSON object, and a JProperty
models a name-value pair contained within a JObject
. Each JObject
has a collection of JProperties
which are its children, while each JProperty
has a Name
and a single child, its Value
.
因此,假设您引用了最里面的JObject
(包含View
,Product
和Offer
属性),则可以获取包含JProperty
的名称,如下所示:
So, assuming you have a reference to the innermost JObject
(containing the View
, Product
and Offer
properties), you can get the name of its containing JProperty
like this:
JProperty parentProp = (JProperty)jObject.Parent;
string name = parentProp.Name; // "Info"
这篇关于在Json.Net中获取JObject的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!