Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active July 5, 2024 02:41
Show Gist options
  • Save relyky/05d8f8f66e769fff30c29da85c77704a to your computer and use it in GitHub Desktop.
Save relyky/05d8f8f66e769fff30c29da85c77704a to your computer and use it in GitHub Desktop.
JsonSerializer, .NET5, json, 中文字不編碼, 換行與縮排, System.Text.Json, Indent
using System;
using System.Text.Json;
var foo = new { ... };
string json = JsonSerializer.Serialize(foo, new JsonSerializerOptions {
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, // 中文字不編碼
WriteIndented = true // 換行與縮排
});
public static class JsonSerializerEx
{
public static string Serialize<TValue>(TValue value, bool UnsafeRelaxedJsonEscaping, bool WriteIndented = false)
{
var options = new JsonSerializerOptions()
{
WriteIndented = WriteIndented // 換行與縮排
};
// 中文字不編碼
if (UnsafeRelaxedJsonEscaping)
options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
return JsonSerializer.Serialize(value, options);
}
}
/// 應用
var foo = new { ... };
string json = JsonSerializerEx.Serialize(foo, UnsafeRelaxedJsonEscaping: true, WriteIndented: true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment