【问题标题】:Add name value pairs to a JObject within a JArray将名称值对添加到 JArray 中的 JObject
【发布时间】:2016-06-05 04:09:32
【问题描述】:
{
    "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() 时它是一个对象..

【问题讨论】:

  • 你用过 myarray[0]["z"] = 9000;

标签: c# json json.net


【解决方案1】:

将数组项转换为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

【讨论】:

  • 谢谢布赖恩! :D 顺便说一句,为什么需要这个?数组项甚至在我执行 Cast (?) 之前就报告为 LinQ.JObject 类型
  • JTokenJObjectJArrayJValue 等的基类。Type 属性在那里,以便您可以找出@ 的类型987654331@ 这样您就可以在需要时适当地投射它。 JToken 本身没有Add 方法,而JObjectJArray 有,因此您必须强制转换为正确的子类才能调用该方法。有意义吗?
  • 这很有意义 :) 再次感谢 Brian 的详细说明
猜你喜欢
  • 2021-12-18
  • 2017-01-22
  • 2019-03-20
  • 1970-01-01
  • 2023-04-06
  • 2021-12-18
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
相关资源
最近更新 更多