Home > OS >  Jobject using .Add in a nested element
Jobject using .Add in a nested element

Time:11-11

If I had a Json Object:

{ 
"data":{
      "SomeArray":[
         {
            "name":"test1"
         },
         {
            "name":"test2"
         },
         {
            "name":"test3"
         }
      ]
   }
}

And this object is Parsed using Jobject.Parse(jsonString);

How would I add a field under data that holds the count of the items in the array to be forwarded tro another system. The count has already been calculated. I just need to add it in like this:

{ 
"data":{
      "Count" : 3,
      "SomeArray" : [

I have tried

myJObject["data"].Add("Count",count);

But .Add does not work here. The only option I see is AddAfterSelf()

Is there no way to just add a simple key value pair without having to create Jproperty first and add it using AddAfterSelf?

Or is the correct way: x["Data"].AddAfterSelf(new JProperty("Count", count));

CodePudding user response:

You could do this by casting the JToken that you get from myJObject["data"] as a JObject. For example:

var data = (JObject)myJObject["data"];
data.Add("Count", 3);

CodePudding user response:

The problem here is that myJObject["data"] returns an JToken which is base class for JObject.

If you're sure that "data" will be always an object, you can do following

var data = myJObject.GetValue("data") as JObject;
data.Add("Count",120);
  • Related