JsonExtensions.cs
1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System.Text.Encodings.Web;
using System.Text.Json;
namespace Rcs.Shared.Utils
{
/// <summary>
/// JSON 序列化扩展方法
/// @author zzy
/// </summary>
public static class JsonExtensions
{
private static readonly JsonSerializerOptions ChineseOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNameCaseInsensitive = true
};
/// <summary>
/// 将对象序列化为 JSON 字符串(保留中文字符,不转义为 Unicode)
/// @author zzy
/// </summary>
public static string ToJsonWithChinese<T>(this T obj)
{
return JsonSerializer.Serialize(obj, ChineseOptions);
}
/// <summary>
/// 将 JSON 字符串反序列化为对象
/// @author zzy
/// </summary>
public static T? FromJson<T>(this string json)
{
if (string.IsNullOrEmpty(json)) return default;
return JsonSerializer.Deserialize<T>(json, ChineseOptions);
}
}
}