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); + } + } +}