Search code examples
c#.netjson.net-coresystem.text.json

dotnet core System.Text.Json unescape unicode string


Using JsonSerializer.Serialize(obj) will produce an escaped string, but I want the unescaped version. For example:

using System;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        var a = new A{Name = "你好"};
        var s = JsonSerializer.Serialize(a);
        Console.WriteLine(s);
    }
}

class A {
    public string Name {get; set;}
}

will produce a string {"Name":"\u4F60\u597D"} but I want {"Name":"你好"}

I created a code snippet at https://dotnetfiddle.net/w73vnO
Please help me.


Solution

  • You need to set the JsonSerializer options not to encode those strings.

    JsonSerializerOptions jso = new JsonSerializerOptions();
    jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
    

    Note that using UnsafeRelaxedJsonEscaping comes with security risks such as XSS attacks.

    Then you pass this options when you call your Serialize method.

    var s = JsonSerializer.Serialize(a, jso);        
    

    Full code:

    JsonSerializerOptions jso = new JsonSerializerOptions();
    jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
    
    var a = new A { Name = "你好" };
    var s = JsonSerializer.Serialize(a, jso);        
    Console.WriteLine(s);
    

    Result:

    enter image description here

    If you need to print the result in the console, you may need to install additional language. Please refer here.