将名称值对添加到JArray中的JObject

时间:2016-06-04 13:29:07

标签: c# json json.net

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

我想将另一对推入things[0],以便它读取

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

我可以轻松修改这样的值:

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

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

我无法弄清楚如何添加/附加到此对象。看来myarray[0]JToken,即使它是GetType()时的对象..

1 个答案:

答案 0 :(得分:5)

将数组项投射到JObject,然后使用Add方法添加新的JProperty。像这样:

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

小提琴:https://dotnetfiddle.net/5Cb5lu