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:
{
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