WMSlite/WmsLite.Api/Common/JsonLongAsStringConverter.cs
zhougf fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

53 lines
1.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WmsLite.Api.Common;
/// <summary>
/// 将 Int64 以 JSON 字符串写出,避免前端 number 精度丢失(Snowflake 等主键)。
/// 反序列化同时支持 JSON 数字与字符串。
/// </summary>
public sealed class JsonLongAsStringConverter : JsonConverter<long>
{
public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.Number => reader.GetInt64(),
JsonTokenType.String => long.Parse(reader.GetString()!, NumberStyles.Integer, CultureInfo.InvariantCulture),
_ => throw new JsonException($"Unexpected token {reader.TokenType} when reading long."),
};
}
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
}
}
public sealed class JsonNullableLongAsStringConverter : JsonConverter<long?>
{
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.Null => null,
JsonTokenType.Number => reader.GetInt64(),
JsonTokenType.String => long.Parse(reader.GetString()!, NumberStyles.Integer, CultureInfo.InvariantCulture),
_ => throw new JsonException($"Unexpected token {reader.TokenType} when reading long?."),
};
}
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
return;
}
writer.WriteStringValue(value.Value.ToString(CultureInfo.InvariantCulture));
}
}