dotnet 核心 System.Text.Json unescape unicode 字符串 [英] dotnet core System.Text.Json unescape unicode string
问题描述
使用 JsonSerializer.Serialize(obj)
会产生一个转义的字符串,但我想要非转义的版本.例如:
使用系统;使用 System.Text.Json;公开课计划{public static void Main(){var a = new A{Name = "你好"};var s = JsonSerializer.Serialize(a);Console.WriteLine(s);}}A类{公共字符串名称{get;放;}}
将产生一个字符串 {Name":u4F60u597D"}
但我想要 {Name":你好"}
我在
如果您需要在控制台中打印结果,您可能需要安装其他语言.请参阅此处.
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":"u4F60u597D"}
but I want {"Name":"你好"}
I created a code snippet at https://dotnetfiddle.net/w73vnO
Please help me.
You need to set the JsonSerializer options not to encode those strings.
JsonSerializerOptions jso = new JsonSerializerOptions();
jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
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:
If you need to print the result in the console, you may need to install additional language. Please refer here.
这篇关于dotnet 核心 System.Text.Json unescape unicode 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!