Last active
July 5, 2024 02:41
-
-
Save relyky/05d8f8f66e769fff30c29da85c77704a to your computer and use it in GitHub Desktop.
JsonSerializer, .NET5, json, 中文字不編碼, 換行與縮排, System.Text.Json, Indent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 // 換行與縮排 | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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