-
-
Save newpost/3343c6185cf010da5ded04e045a8460b 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