Search code examples
servicestackservicestack-text

ServiceStack does not escape control characters in JSON


ServiceStack's JsonSerializer does not seem to encode control characters correctly.

For example, this C# expression....

JsonSerializer.SerializeToString(new { Text = "\u0010" })

... evaluates to this...

{"Text":"?"}

... where the "?" is the literal control character.

Instead, according to http://www.json.org it should evaluate to this:

{"Text":"\u0010"}

Is this a known bug or am I missing something?

The bad JSON output by my services is causing errors during deserialization by my service consumers.


Solution

  • You need to tell the serializer to escape unicode characters.

    JsConfig.EscapeUnicode = true;
    JsonSerializer.SerializeToString(new{Text = "\u0010"});
    

    The above evaluates to this:

    {"Text":"\u0010"}