简体   繁体   English

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

[英]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[0]以便读取

"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() .. 看起来myarray[0]是一个JToken ,即使我执行GetType()时它也是一个对象。

Cast the array item to a JObject , then use the Add method to add a new JProperty . 将数组项转换为JObject ,然后使用Add方法添加新的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 小提琴: https : //dotnetfiddle.net/5Cb5lu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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