7

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

1
  • 1
    When you invoke JsonConvert.SerializeObject(MyObject) , MyObject here is serialized as a string, thus the NewNode here is presenting itself as a string quoted. :) Commented Sep 6, 2016 at 15:07

2 Answers 2

8

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());
Sign up to request clarification or add additional context in comments.

2 Comments

A man chooses, a slave obeys! anyways please look at the above edit. This is returning an error.
Ooops. Sorry dude. Didnt know that was a collection. Hold on. Not sure i can type code segment properly through a phone
1
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            JObject tempvar= JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");
            string cpu = (string)tempvar["CPU"];          // Intel
            string firstDrive = (string)tempvar["Drives"][0];   // DVD read/writer
IList<string> allDrives = tempvar["Drives"].Select(t => (string)t).ToList();
            // DVD read/writer
            // 500 gigabyte hard drive

            tempvar["Drives"][0].AddAfterSelf("new node");
//tempvar json with new node
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.