JObject nested property

烈酒焚心 提交于 2019-12-05 21:04:00

问题


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?


回答1:


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



回答2:


Just carry on as you are, and nest them in another level:

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

JObject parent = new JObject(new JProperty("input", job));

parent.ToString() now gives:

{ "input": { "website/url": "http://www.google.com" } }



来源:https://stackoverflow.com/questions/30126167/jobject-nested-property

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