Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of a JObject in Json.Net

Tags:

c#

linq

json.net

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?

like image 948
AnotherDeveloper Avatar asked Jun 02 '14 18:06

AnotherDeveloper


People also ask

How can I get JToken name?

You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject . Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty , you can get its Name .

How do I find JObject value?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

How do you iterate over a JObject?

If you look at the documentation for JObject , you will see that it implements IEnumerable<KeyValuePair<string, JToken>> . So, you can iterate over it simply using a foreach : foreach (var x in obj) { string name = x. Key; JToken value = x.

Is a JObject a JToken?

A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.


1 Answers

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"
like image 70
Brian Rogers Avatar answered Sep 20 '22 11:09

Brian Rogers