简体   繁体   中英

Jobject using .Add in a nested element

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));

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM