使用JsonSerializer.Serialize(obj)将生成一个转义字符串,但我想要未转义的版本.例如:

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.

推荐答案

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:

enter image description here

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

Json相关问答推荐

使用Jolt库对多个数组进行嵌套循环

Oracle plsql:如何将json文件加载到嵌套表中

将PostgreSQL转换为JSON对象

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

419(未知状态)使用laravel处理PUT请求

如何使用Powershell查找所有包含特定键值对的JSON对象并迭代所有对象?

xidel:是否可以从 JSON 对象中检索特定的嵌套值?

判断golang中解析的json响应中是否存在所需的json键(不是值)

如何使用 Swiftui 判断 JSON 是否缺少键值对

杰克逊 2.0 和 Spring 3.1

如何使用 gson 将数据保存在 json 文件中?

如何在 jQuery 中循环遍历 JSON 数组?

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

可以在 SharedPreferences 中保存 JSON 数组吗?

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

春天:返回@ResponseBodyResponseEntity>

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象

用 JSON 编写 HTML 字符串