-
Notifications
You must be signed in to change notification settings - Fork 447
/
Copy pathJsonBufferSerializer.cs
37 lines (34 loc) · 1.56 KB
/
JsonBufferSerializer.cs
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.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
namespace WebApiClientCore.Serialization
{
/// <summary>
/// json序列化工具
/// </summary>
public static class JsonBufferSerializer
{
/// <summary>
/// 默认选项
/// </summary>
private static readonly JsonSerializerOptions defaultOptions = new();
/// <summary>
/// 将对象序列化为Utf8编码的Json到指定的BufferWriter
/// </summary>
/// <param name="bufferWriter">buffer写入器</param>
/// <param name="obj">对象</param>
/// <param name="options">选项</param>
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static void Serialize(IBufferWriter<byte> bufferWriter, object? obj, JsonSerializerOptions? options)
{
if (obj == null)
{
return;
}
options ??= defaultOptions;
var utf8JsonWriter = Utf8JsonWriterCache.Get(bufferWriter, options);
JsonSerializer.Serialize(utf8JsonWriter, obj, obj.GetType(), options);
}
}
}