JSON add node to an existing JObject

Could you kindly try with this?

mainJson.Add("NewNode", JObject.FromObject(MyObject));
File.WriteAllText("myfile.json", mainJson.ToString());

When you are doing JsonConvert.SerializeObject(MyObject) it serializes MyObject and in the process you get a string out of it.

When you assign mainJson.Add("NewNode", JsonConvert.SerializeObject(MyObject)); you're assigning a string to NewNode. Thus you get a quoted string that represents serialized MyObject

Update:

JArray.FromObject is the method you'd want to look for if you want to convert your collection to a JArray. In that case the segment would look something like

mainJson.Add("NewNode", JArray.FromObject(obsColl));
File.WriteAllText("myfile.json", mainJson.ToString());

Tags:

C#

Json

Json.Net