首页 > 解决方案 > 将 JToken 添加到 JObject 中的特定 JsonPath

问题描述

我有一个看起来像这样的 JObject..

{
    "address": [
        {
            "addressLine1": "123",
            "addressLine2": "124"
        },
        {
            "addressLine1": "123",
            "addressLine2": "144"
        }
    ]
}

对于 JsonPath address[2],我想将以下 JObject 添加到address数组中。

{
     "addressLine1": "123",
     "addressLine2": "144"
}

我想做类似 json.TryAdd(jsonPath, value);

如果索引处有一个对象,2我会很容易做到

var token = json.SelectToken(jsonPath);
if (token != null && token .Type != JTokenType.Null)
{
      token .Replace(value);
}

但由于该索引不存在,我将得到 null 作为token

标签: c#json

解决方案


正如我们在评论部分提到的,如果索引不存在,您不能将项目添加/替换到索引。在这种情况下,您需要将项目添加为新成员JArray,或者您可以使用Insert在指定索引处添加项目:

JObject value = new JObject();
value.Add("addressLine1", "123");
value.Add("addressLine2", "144");

JObject o = JObject.Parse(json);
int index = 2;
JToken token = o.SelectToken("address[" + index + "]");
if (token != null && token.Type != JTokenType.Null)
{
    token.Replace(value);
}
else //If index does not exist than add to Array
{
    JArray jsonArray = (JArray)o["address"];
    jsonArray.Add(value);
    //jsonArray.Insert(index, value); Or you can use Insert

}

推荐阅读