Nono Nono - 17 days ago 8
C# Question

C# - Add value to json string

I have an object and I am generating a json string of that object with the following code:

string json = JsonConvert.SerializeObject(myObject);


JsonConvert is from Newtonsoft.Json. I want to add a new value to that json string but only to the string and not to the object. How can I do that? (I'm new to C#)

Answer

Serialization is just one of the things the Newtonsoft library does. You can also use the JsonReader and JsonWriter as well as several other libraries. The one you're probably looking for is the JObject. You can parse JSON and modify it like the example here: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

From the link:

JObject rss = JObject.Parse(json);
JObject channel = (JObject)rss["channel"];
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));