c# - 将 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
解决方案
正如我们在评论部分提到的,如果索引不存在,您不能将项目添加/替换到索引。在这种情况下,您需要将项目添加为新成员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
}
推荐阅读
- python - Python中奇怪的字符串格式
- python - django modeladmin中的django多表继承
- extjs - Extjs Grid ApplyState not reflecting the changes | Hide issue
- go - go - 如何从x509证书公钥中获取字符串?
- angular - 在 for 循环中动态设置样式
- c# - 如何使用 RabbitMQ 官方客户端异步发布和接收消息?
- api - 从 reddit api 获取时如何修复“错误 503 cdn 错误”?
- java - 如何在 Firebase 数据库 Android 上获取具有相似子节点的所有父节点?
- c - Gstreamer C 代码因流停止而失败,原因未协商 (-4)
- c++ - 预处理字符串连接