20 lines
779 B
C#
20 lines
779 B
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace F9WebAiTest.Api.JsonConverters;
|
|
|
|
/// <summary>
|
|
/// 将 long 序列化为字符串,避免雪花 ID(超过 JS Number 安全整数 2^53)在前后端传递时丢失精度。
|
|
/// 反序列化时兼容字符串与数字两种形式。
|
|
/// </summary>
|
|
public class LongToStringJsonConverter : JsonConverter<long>
|
|
{
|
|
public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
=> reader.TokenType == JsonTokenType.String
|
|
? long.Parse(reader.GetString()!)
|
|
: reader.GetInt64();
|
|
|
|
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
|
|
=> writer.WriteStringValue(value.ToString());
|
|
}
|