0

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

How would I then add the data back into the original JObject, just by doing myJObject["data"] = data; ?
@Bike_dotnet you should not do it. it will be automatically present in myJObject because it is referenced data type.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.