将一个 JToken 添加到 JObject 中的特定 JsonPath 中。

huangapple go评论68阅读模式
英文:

Add a JToken to a specific JsonPath in a JObject

问题

我有一个类似这样的 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);
}

但是,由于该索引不存在,我将会得到 token 的值为 null

英文:

I have a JObject that looks like this..

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

for JsonPath address[2], I want to add the following JObject to the address array.

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

I want to do something like json.TryAdd(jsonPath, value);

If there was an object at index 2 i would have easily done

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

but since that index does not exist I'll get null as the value of token

答案1

得分: 1

以下是您要翻译的内容:

正如我们在评论部分提到的,如果索引不存在,您不能添加/替换项目到索引。在这种情况下,您需要将项目添加为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
}
英文:

As we mentioned on comment section, you can not add/replace item to index if index does not exist. In that case you need to add item as a new member of JArray instead, or you can use Insert to add item at the specified index :

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

}

huangapple
  • 本文由 发表于 2020年1月6日 17:00:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定