Reputation: 77
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.
Upvotes: 1
Views: 717
Reputation: 23298
You can use the following code to add a new token after type
var jObject = JObject.Parse(json);
jObject["description"]?["StarWars"]?["type"]?.Parent?.AddAfterSelf(new JProperty("add", true));
JObject
indexer returns a JValue
of property, not the property itself, so you should access its Parent
to call AddAfterSelf
method.
Also, in your code object
is invalid name for variable
Upvotes: 3