Search code examples
c#json.net

JSON file shows extra backslashes after appending a new object to an array


I have a school.json file with this structure:

{
  "schoolConfig": [

      {
        "schoolTypeCode": "C1",                
        "schools": [
          {
            "schoolId": 456,                  
            "config": [
              {
                "name": "Classes",
                "value": [
                  {
                    "id": 1                           
                  },
                  {
                    "id": 2
                  }
                ]
              }
            ]
          },
          {
            "schoolId": 123,                   
            "config": [
              {
                "name": "Classes",
                "value": [
                  {
                    "id": 11                            
                  }                  
                ]
              }
            ]
          }
        ]
      },
      {
        "schoolTypeCode": "C2",                
        "schools": [
          {
            "schoolId":50,                    
            "config": [
              {
                "name": "Classes",
                "value": [
                  {
                    "id": 12
                  }
                ]
              }
            ]
          },
          {
            "schoolId": 10,                  
            "config": [
              {
                "name": "Classes",
                "value": [                  
                  {
                    "id": 10
                  }
                ]
              }
            ]
          }
        ]
      }    
  ]
}

I want to append to the JSON file which will change the config values for any filtered result. So, for example, the output JSON will have:

"value": [
  {
    "id": 1                           
  },
  {
    "id": 2
  }
  {
    "id": 5
  }
]

The c# code written to replace the existing json with the new one is:

string json = File.ReadAllText(jsonFilePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
JToken classes = jsonObj.SelectToken("$.schoolConfig[?(@.schoolTypeCode == 'C1')].schools[?(@.schoolId == 456)].config[?(@.name == 'Classes')]");

List<JToken> appList = classes["value"].ToList();

var itemToAdd = new JObject();
itemToAdd["id"] = 5;
appList.Add(itemToAdd);

classes["value"] = Newtonsoft.Json.JsonConvert.SerializeObject(appList).ToString();

string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(jsonFilePath, output);

The file gets modified except that the value is shown in one line (with no indentation or formatting) as

"value": "[{\"id\":1},{\"id\":2},{\"id\":5}]"

How do I ensure that the JSON file does not show extra backslashes before the quotes and is rendered in proper format as written above. Please advise.


Solution

  • The problem is that you are extracting the value array from the classes object as a List<JToken> instead of as a JArray. Then you are serializing the list to a string before adding it back to classes. If you just cast it to JArray instead of converting it to List<JToken>, you can modify the JArray directly.

    Change this line:

    List<JToken> appList = classes["value"].ToList();
    

    to this:

    JArray appList = (JArray)classes["value"];
    

    and remove this line:

    classes["value"] = Newtonsoft.Json.JsonConvert.SerializeObject(appList).ToString();
    

    Working demo: https://dotnetfiddle.net/TO2zqt