Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JObject nested property

Tags:

json

c#

json.net

I am trying to make a json object like this with JObject:

{
    "input": {
        "webpage/url": "http://google.com/"
    }
}

I can add properties like:

JObject job = new JObject(
                new JProperty("website/url", "http://www.google.com") );

But any time I try to nest an object inside another object so I can have the parent "input" it throws an exception.

How do you make nested properties with JObject?

like image 934
Guerrilla Avatar asked May 08 '15 14:05

Guerrilla


People also ask

Does JSON allow nested objects?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.

What does nested mean in JSON?

Nested JSON is simply a JSON file with a fairly big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.

What is a JObject?

JObject. It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft.

What is JToken in C#?

JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.


1 Answers

Probably the most straightforward way would be:

var input = new JObject();

input.Add("webpage/url", "http://google.com");

var obj = new JObject();

obj.Add("input", input);

Which gives you:

{
  "input": {
    "webpage/url": "http://google.com"
  }
}

Another way would be:

var input = new JObject
{
    { "webpage/url", "http://google.com" }
};

var obj = new JObject
{
    { "input", input }
};

... Or if you wanted it all in one statement:

var obj = new JObject
{
    {
        "input",
        new JObject
        {
            { "webpage/url", "http://google.com" }
        }
    }
};
like image 183
Andrew Whitaker Avatar answered Sep 27 '22 18:09

Andrew Whitaker