Search code examples
c#jsonjson.net

How to append Jobject to the Jarray of Jproperty?


I am creating new Jobject as,

var testresult = new JObject(new JProperty("Name", "John"),
                    new JProperty("Nums", new JArray())); 

Result is:

{
  "Name": "John",
  "Nums": []
}

And I am trying to add another JObject inside of the JArray of Jproperty "Nums".

{
      "Name": "John",
      "Nums": [{"tl1": "tr1"}, {"tl2": "tr2"}]
 }

I have tried testresult.Property.Add , AddAfterSelf style but I think my main problem is I cannot access the right side of JProperty "Nums". What can I try or look for?


Solution

  • you can create all in one line

    var testresult = new JObject(new JProperty("Name", "John"), new JProperty("Nums", new JArray(
    new JObject(new JProperty("tl1", "tr1") ),new JObject(new JProperty("tl2", "tr2") ))));
    

    or if you want to add new items later, you can do it in one line too

    testresult["Nums"]=new JArray(new JObject(new JProperty("tl1", "tr1") ), 
    new JObject(new JProperty("tl2", "tr2")));
    

    or if you want to add an array of new items to an exising array, you can use Merge

    ((JArray) testresult["Nums"]).Merge(new JArray(new JObject(new JProperty("tl1", "tr1")), new JObject(new JProperty("tl2", "tr2"))));
    

    or Add if you want to add one more item to array

    ((JArray) testresult["Nums"]).Add( new JObject(new JProperty("tl1", "tr1")));
    

    result

    {
      "Name": "John",
      "Nums": [
        {
          "tl1": "tr1"
        },
        {
          "tl2": "tr2"
        }
      ]
    }