是否可以将数组添加到 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然后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; }我在这条线上遇到了一个例外:使用示例: var result = jobject.AddArray("channel.nested", "upgrademe", "please");上面说了以下内容:找到对象“channel.nested”,当 upgrademe==please 时,添加一个同级节点作为空数组我们如何有条件地将数组对象添加到 json 负载中?
1 回答
慕容3067478
TA贡献1773条经验 获得超3个赞
由于您要将新属性添加到对象中。你不需要使用JValue
直接使用JProperty
即可:
AddAfterSelf(new JProperty("emptyArray", new JArray()))
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报
0/150
提交
取消