在Json.Net中获取JObject的名称 [英] Get the name of a JObject in Json.Net

查看:297
本文介绍了在Json.Net中获取JObject的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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对象建模,而JPropertyJObject中包含的名称-值对建模.每个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(包含ViewProductOffer属性),则可以获取包含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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆