Search code examples
c#jsonencodingjson.netjsonserializer

How to encode a string into Json string text?


When I try to retrieve SQL table content in to a JSON format in C# eg: the content Baden-Württemberg is retrived as a "Baden-W\u00FCrttemberg" after JSON serilize. I try this

byte[] bytes = Encoding.UTF8.GetBytes(input);
input = Encoding.UTF8.GetString(bytes);
var output = JsonConvert.SerializeObject(input);

But I get "Baden-Württemberg" I really want like demo http://www.percederberg.net/tools/text_converter.html, The input type is plaintext, ISO-Latin-1

Baden-Württemberg

and output type is JSON/Javascript/Java - String text

"Baden-W\u00FCrttemberg"

How could I do in C# .Net


Solution

  • You can tell JSON.NET to escape all non-ASCII characters like this:

    var json = JsonConvert.SerializeObject("Baden-Württemberg", new JsonSerializerSettings
    {
        StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
    });
    

    The value of json will then be:

    "Baden-W\u00fcrttemberg"
    

    And you can send the resultant JSON string through an ASCII-encoded channel.