Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add name value pairs to a JObject within a JArray

Tags:

json

c#

json.net

{
    "x": null,
    "y": null,
    "z": null,
    "things": [
        {
            "x": 1,
            "y": 1
        },
        {
            "x": 1,
            "y": 6
        }
    ]
}

I want to push another pair into things[0] so that it reads

"things": [
{
    "x": 1,
    "y": 1,
    "z": 9000
},

I can easily modify the values like this:

JObject myobject = JObject.Parse(responseString);
JArray myarray = (JArray)myobject["things"];

myarray[0]["x"] = 9000;

I can't figure out how to add/append to this object instead. It appears myarray[0] is a JToken, even though it is an object when I do GetType()..

like image 327
Didier Drogba Avatar asked Sep 15 '25 14:09

Didier Drogba


1 Answers

Cast the array item to a JObject, then use the Add method to add a new JProperty. Like so:

JObject myobject = JObject.Parse(responseString);
JArray myarray = (JArray)myobject["things"];

JObject item = (JObject)myarray[0];
item.Add(new JProperty("z", 9000));

Console.WriteLine(myobject.ToString());

Fiddle: https://dotnetfiddle.net/5Cb5lu

like image 87
Brian Rogers Avatar answered Sep 17 '25 03:09

Brian Rogers