Get the name of a JObject in Json.Net

僤鯓⒐⒋嵵緔 提交于 2019-12-07 03:09:29

问题


I have a JObject equal to:

"Info":
{
    "View":"A",
    "Product":"B",
    "Offer":"Offer1",
    "Demo":"body {background-color:red;} #box {border:dotted 50px red;}",
    "Log":false
}

How can I return the name of the object, "Info"?

I am currently using the Path property like so:

jObject.Name = jObject.Path.Substring(jObject.Path.jObject('.') + 1);

Is there a better way to do this?


回答1:


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
    }
}

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.

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"


来源:https://stackoverflow.com/questions/24000572/get-the-name-of-a-jobject-in-json-net

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