c# - Add a new value to a JSON
问题描述
I've got the following JSON:
string json = @"{
'title': ['StarWars'],
'description': {'StarWars': {'type': 'blog'}}
}";
I want to add a new value to the description value such as:
string json = @"{
'title': ['StarWars'],
'description': {'StarWars': {'type': 'blog', 'add': true}}
}";
The property StarWars
inside description
property is always the same as the value of title
.
How could I add the new property?
I parsed the JSON:
var jObject = JObject.Parse(json);
object.Property("description").AddAfterSelf(new JProperty("add", true));
And I know that's how you add a new property to a json, but I'm not sure how to add a property to a json that's encapsulated in another json.
解决方案
您可以使用以下代码在之后添加新令牌type
var jObject = JObject.Parse(json);
jObject["description"]?["StarWars"]?["type"]?.Parent?.AddAfterSelf(new JProperty("add", true));
JObject
indexer 返回一个JValue
of 属性,而不是属性本身,因此您应该访问它Parent
的调用AddAfterSelf
方法。
此外,在您的代码object
中,变量的名称无效
推荐阅读
- javascript - Javascript文件在github页面上不起作用
- c++ - 如何在带有 tensorflow 的 mkl 中使用 libtbb.so
- excel-formula - 在excel中对单元格进行逻辑计数
- css - bootstrap 的 glyphicon 没有表现出来
- android - 寻求栏设置自定义最小值
- android - 我有一个选项卡式活动,它在纵向模式下工作正常,但在横向模式下停止显示数据。并且滑动也不会在标签中完美运行
- php - Paypal PHP Rest API SDK - 现在似乎没有工作
- sql - SQL Server 中 Conc() 的等价物是什么
- awk - 如果我将字段清零,为什么 awk 会执行不同的 OFS 解析?
- c++ - 函数中调用的构造函数的顺序