Search code examples
jsonjson.net

Enumerating of JObject of NewtonSoft.Json loses '\' character in C#


I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:

{"json":"{\"count\":\"123\"}"}
  1. The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".

  2. The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.

The testing code I used is like this.

[TestMethod()]
public void JsonParseTest()
{
   var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
   var jObject = JObject.Parse(json);
   Console.WriteLine($"json : {json}");
   Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
   Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}

We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)

EDIT 1 The version of NewtonSoft is 12.0.3 released in 2019.11.09.


Solution

  • The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.

    If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):

    {"json":"{\\\"count\\\":\\\"123\\\"}"}
    

    with leads to the C# code:

    var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";