dotnet核心System.Text.Json Unscape Unicode字符串 [英] dotnet core System.Text.Json unescape unicode string

查看:58
本文介绍了dotnet核心System.Text.Json Unscape Unicode字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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; set;}
}

将产生字符串 { Name : \u4F60\u597D} 但我要 { Name:你好}



我在



如果需要在控制台中打印结果,则可能需要安装其他语言。请在此处


Using JsonSerializer.Serialize(obj); will produce a 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.

解决方案

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 Unscape Unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆