I am trying to add a new node to an existing JSON JObject, but when I add it does not format correctly. It adds quotes around the entire node, and \ are put in place.
Background:
I am loading a JSON file, doing some logic then adding a node back in. Figured I can do it like this:
mainJson.Add("NewNode", JsonConvert.SerializeObject(MyObject));
File.WriteAllText("myfile.json", mainJson.ToString());
Problem is that this is the result:
{
"JSONFile": [
{
"More": "Nodes",
"InThe": "File"
}
],
"Customers": "{\"FirstName\":\"Mike\",\"LastName\":\"Smith\"},{\"FirstName\":\"Jane\",\"LastName\":\"Doe\"}",
}
I know that my JsonConvert.SerializeObject(MyObject) is working if I do this:
string json = JsonConvert.SerializeObject(MyObject);
File.WriteAllText("myfile2.json" json);
The result is this:
[
{
"FirstName": "Mike",
"LastName": "Smith"
},
{
"FirstName": "Jane",
"LastName": "Doe"
}
]
What am I missing?
edit: Following @Swagata Prateek comment of;
mainJson.Add("Customers",JObject.FromObject(MyObject));
An unhandled exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll
Additional information: Object serialized to Array. JObject instance expected.
I should note that MyObject is actual ObservableCollection if that makes a difference
JsonConvert.SerializeObject(MyObject),MyObjecthere is serialized as a string, thus theNewNodehere is presenting itself as a string quoted. :)