Skip to content

Instantly share code, notes, and snippets.

@newpost
Forked from relyky/JsonSerializer.cs
Created July 5, 2024 02:41
Show Gist options
  • Save newpost/3343c6185cf010da5ded04e045a8460b to your computer and use it in GitHub Desktop.
Save newpost/3343c6185cf010da5ded04e045a8460b 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