是否可以将数组添加到json有效负载?
例如,假设这是我的有效载荷:
string json = @"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': [{'something':'awesome'},{'a':'b'}],
'item': [],
'nested':[{'upgrademe':'please'}, {'upgrademe':'no'}]
}
}";
我想要的结果将是这样的:
string json = @"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': [{'something':'awesome'},{'a':'b'}],
'item': [],
'nested':[{'upgrademe':'please', 'emptyArray':[]}, {'upgrademe':'no'}]
}
}";
对于每个channel.nested
== upgrademe
的{{1}},我想添加一个像please
这样的空数组。
之前:
[]
之后:
'nested':[{'upgrademe':'please'}, {'upgrademe':'no'}]
我当前的实现方式:
'nested':[{'upgrademe':'please', 'emptyArray':[]}, {'upgrademe':'no'}]
我在此行遇到异常:
用法示例:
public static JObject AddArray(this JObject jObject, string path, string key, string value)
{
var obs = jObject.SelectToken(path);
if (obs == null)
{
return jObject;
}
foreach (var jsonObject in obs)
{
if (jsonObject.SelectToken(key).ToString().ToLower() != value.ToLower())
{
continue;
}
jObject.SelectToken(path).Parent.AddAfterSelf(new JValue(new JProperty("emptyArray", new JArray())));
}
return jObject;
}
上面说的是以下内容:
找到对象“ channel.nested”,并在upgrademe == please时,添加一个同级节点作为空数组
我们如何有条件地将数组对象添加到json有效负载?
答案 0 :(得分:2)
由于要在对象中添加新属性。您不需要使用JValue
只需直接使用JProperty
:
AddAfterSelf(new JProperty("emptyArray", new JArray()))