0
static void Main(string[] args)
{
    var newLineChar = Char.Parse("\u2028");
    var jsonStr = @"{""value"":""some chars " + newLineChar + @"""}";

    var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonStr);

    var jsonStrAfterParse = jObject.ToString(Newtonsoft.Json.Formatting.None);
}

I have a JSON string like:

"{\"value\":\"some chars \u2028\"}"

After I try to parse it using Newtonsoft.Json, I got the JSON:

"{\"value\":\"some chars \\u2028\"}"

The Line Separator char '\u2028' was parsed to '\\u2028'. I cannot make sure whether any other chars have the same issue. Can anyone help with this? Thanks.

Pic in immediate window

jsonStr in text visualizer

jsonStrAfterParse in text visualizer

erYYer
  • 3
  • 2

1 Answers1

1

In the comments you established that it's expected behavior, but I thought I'd go into why based on the source code.

Your input string is not valid JSON because of the unescaped control character \u2028, but NewtonSoft.Json is gracefully handling the bad input, and giving correct output of \\u2028 when you ask it to serialize for you.

For the deserialization, it doesn't care that you didn't escape it. It just goes ahead and includes it with your string. No biggie.

But when you ask it to serialize the string for you with .ToString(Newtonsoft.Json.Formatting.None)--which is a Newtonsoft extension method--its job is to give you valid JSON, and by golly, that's what it's going to do, giving you the \\u2028 you see.

Chad Hedgcock
  • 11,125
  • 3
  • 36
  • 44