Search This Blog

Wednesday, March 8, 2017

Adding a property to a json object (either at the beginning or at the end) using Newtonsoft

Somewhere in my app I receive a JSON object, and I needed to add to it a couple of additional properties. Appending them turned out to be pretty straightforward. To add them to the beginning was not that quick.

Here's the code that does both:

string json = @"
{
    a: '123',
    b: 'avraham',
    c: { c1: 1111, c2: 'dada' }
}
"
;


var jsObject = JObject.Parse(json);
jsObject.Add("newProp", JToken.FromObject("I am a form title"));

Console.WriteLine(jsObject.ToString(Newtonsoft.Json.Formatting.Indented));
Console.WriteLine("------------- Adding property to the beginning of JSON  -----------------");

/* ------ does not work ------*/
//jsObject.AddFirst(JToken.FromObject("{formTitle: 'aaaaa'}"));
//jsObject.AddFirst("d2d2d2");
//jsObject.AddAfterSelf(JToken.FromObject("{formTitle: 'aaaaa'}"));

JObject newJObject = new JObject
(
    new JProperty("formTitle""I am a form title"),
    jsObject.Properties()
);
Console.WriteLine(newJObject.ToString(Newtonsoft.Json.Formatting.Indented));
Console.WriteLine("--------- Merging two JObjects (if the properties exist, they will be replaced/overwritten, if not, added ----------");

JObject jObjII = JObject.Parse("{x: 'x Value'}");
jObjII.Merge(jsObject);

Console.WriteLine(jObjII.ToString(Newtonsoft.Json.Formatting.Indented));

Output:


No comments:

Post a Comment