将名称值对添加到JArray中的JObject [英] Add name value pairs to a JObject within a JArray

查看:278
本文介绍了将名称值对添加到JArray中的JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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;

我不知道如何添加/附加到该对象.看来myarray[0]JToken,即使我执行GetType()时它是一个对象.

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

推荐答案

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

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

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

这篇关于将名称值对添加到JArray中的JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆