首页 > 解决方案 > 是否有 System.Text.Json 属性只允许有效的枚举值?

问题描述

我有一个枚举:

public enum TaxType : byte
{
    None = 0,
    GSTCanada = 5,
    HSTOntario = 13,
    HSTOther = 15
}

它在 json 中由一个数字给出。例如:

{"TaxType": 13, ...}
public class OrderInfo
{
    public TaxType TaxType { get; set; }
    /// ...
}

它将成功反序列化,但如果值为NOT (0 OR 5 OR 13 OR 15).

这可以通过使用属性来实现System.Text.Json吗?

标签: c#jsonjson-deserializationsystem.text.json

解决方案


您可以为您的枚举创建一个自定义转换器,如下所示:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

var jsonOpt = new JsonSerializerOptions();
jsonOpt.Converters.Add(new CustomEnumConverter());
Console.WriteLine(JsonSerializer.Deserialize<OrderInfo>("{\"TaxType\":14}", jsonOpt).TaxType);

public enum TaxType
{
    None = 0,
    GSTCanada = 5,
    HSTOntario = 13,
    HSTOther = 15
}

public class OrderInfo
{
    public TaxType TaxType { get; set; }
}

public class CustomEnumConverter : JsonConverter<TaxType>
{
    public override TaxType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetInt32();
        if (Enum.IsDefined(typeToConvert, value))
        {
            return (TaxType) value;
        }
        throw new Exception("Value is invalid");
    }

    public override void Write(Utf8JsonWriter writer, TaxType value, JsonSerializerOptions options)
    {
        writer.WriteNumber("taxType", (decimal)(int)value);
    }
}

显然这不是完全通用的,你需要做一些工作,但你明白了。


推荐阅读