From eafce7e20f3414d47a1cff5796b41084072862f0 Mon Sep 17 00:00:00 2001 From: df123 Date: Tue, 5 May 2026 23:20:30 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20PrizegradesItemDto.?= =?UTF-8?q?Type=20=E7=9A=84=20JsonConverter=20=E8=BF=90=E8=A1=8C=E6=97=B6?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E4=B8=8D=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - IntToStringConverter 继承 JsonConverter 但 Type 属性是 string 类型,运行时报错 - 创建 FlexibleStringConverter (JsonConverter) 替代,支持 JSON Number/String/Null 统一转为 string --- .../DTOs/Lottery/PrizegradesItemDto.cs | 2 +- .../Infrastructure/FlexibleStringConverter.cs | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 src/DFApp.Web/Infrastructure/FlexibleStringConverter.cs diff --git a/src/DFApp.Web/DTOs/Lottery/PrizegradesItemDto.cs b/src/DFApp.Web/DTOs/Lottery/PrizegradesItemDto.cs index 5754551e..d639c987 100644 --- a/src/DFApp.Web/DTOs/Lottery/PrizegradesItemDto.cs +++ b/src/DFApp.Web/DTOs/Lottery/PrizegradesItemDto.cs @@ -7,7 +7,7 @@ public class PrizegradesItemDto { [JsonPropertyName("type")] - [JsonConverter(typeof(IntToStringConverter))] + [JsonConverter(typeof(FlexibleStringConverter))] public string? Type { get; set; } [JsonPropertyName("typenum")] diff --git a/src/DFApp.Web/Infrastructure/FlexibleStringConverter.cs b/src/DFApp.Web/Infrastructure/FlexibleStringConverter.cs new file mode 100644 index 00000000..2af1d414 --- /dev/null +++ b/src/DFApp.Web/Infrastructure/FlexibleStringConverter.cs @@ -0,0 +1,28 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace DFApp.Web.Infrastructure +{ + /// + /// 灵活的字符串转换器,能将 JSON 中的数字和字符串都转换为 C# string + /// + public class FlexibleStringConverter : JsonConverter + { + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + return reader.GetString(); + if (reader.TokenType == JsonTokenType.Number) + return reader.GetInt32().ToString(); + if (reader.TokenType == JsonTokenType.Null) + return null; + throw new JsonException($"意外的 JSON 令牌类型: {reader.TokenType},期望字符串、数字或null。"); + } + + public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); + } + } +}