Didier Drogba Didier Drogba - 5 months ago 48
JSON Question

Add name value pairs to a JObject within a JArray

{
"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()
..

Answer

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

Comments