Home > Back-end >  How to append Jobject to the Jarray of Jproperty?
How to append Jobject to the Jarray of Jproperty?

Time:12-29

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?

CodePudding user response:

JArray has an Add method. You can access the JArray like so:

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

I've assumed the object should be {"tl1":"tr1"} since {"tl1", "tr1"} isn't a valid JSON object.

Try it online

CodePudding user response:

You can either initialize the JArray or use Add:

        JArray arr = new JArray()
        {
            new JObject()
            {
                new JProperty("tl1", "tr1")
            }
        };
        
        arr.Add(new JObject()
        {
            new JProperty("tl2", "tr2")
        });

        JObject obj = new JObject()
        {
            new JProperty("Name", "John"),
            new JProperty("Nums", arr)
        };

        Console.WriteLine(obj);

which produces:

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

   

CodePudding user response:

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"
    }
  ]
}
  • Related