diff --git a/server/HoneyBox/src/HoneyBox.Model/Converters/StringToIntConverter.cs b/server/HoneyBox/src/HoneyBox.Model/Converters/StringToIntConverter.cs new file mode 100644 index 00000000..7e0ba432 --- /dev/null +++ b/server/HoneyBox/src/HoneyBox.Model/Converters/StringToIntConverter.cs @@ -0,0 +1,44 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace HoneyBox.Model.Converters; + +/// +/// JSON转换器:将字符串或空值转换为int +/// +public class StringToIntConverter : JsonConverter +{ + public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var stringValue = reader.GetString(); + if (string.IsNullOrEmpty(stringValue)) + { + return 0; + } + if (int.TryParse(stringValue, out var result)) + { + return result; + } + return 0; + } + + if (reader.TokenType == JsonTokenType.Number) + { + return reader.GetInt32(); + } + + if (reader.TokenType == JsonTokenType.Null) + { + return 0; + } + + return 0; + } + + public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) + { + writer.WriteNumberValue(value); + } +} diff --git a/server/HoneyBox/src/HoneyBox.Model/Models/Welfare/WelfareModels.cs b/server/HoneyBox/src/HoneyBox.Model/Models/Welfare/WelfareModels.cs index 00c9ce69..5f44bace 100644 --- a/server/HoneyBox/src/HoneyBox.Model/Models/Welfare/WelfareModels.cs +++ b/server/HoneyBox/src/HoneyBox.Model/Models/Welfare/WelfareModels.cs @@ -550,6 +550,7 @@ public class WelfareBuyRequest /// 商品ID /// [System.Text.Json.Serialization.JsonPropertyName("goods_id")] + [System.Text.Json.Serialization.JsonConverter(typeof(HoneyBox.Model.Converters.StringToIntConverter))] public int GoodsId { get; set; } /// @@ -580,6 +581,7 @@ public class WelfareBuyRequest /// 优惠券ID /// [System.Text.Json.Serialization.JsonPropertyName("coupon_id")] + [System.Text.Json.Serialization.JsonConverter(typeof(HoneyBox.Model.Converters.StringToIntConverter))] public int CouponId { get; set; } }