英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论