首页 > 解决方案 > 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.

标签: c#jsonjson.net

解决方案


您可以使用以下代码在之后添加新令牌type

var jObject = JObject.Parse(json);
jObject["description"]?["StarWars"]?["type"]?.Parent?.AddAfterSelf(new JProperty("add", true));

JObjectindexer 返回一个JValueof 属性,而不是属性本身,因此您应该访问它Parent的调用AddAfterSelf方法。

此外,在您的代码object中,变量的名称无效


推荐阅读