C# Json 类型转换器 枚举和 string 、int 类型互转

2022年7月18日 2644点热度 4人点赞 0条评论
内容纲要

定义转换器:

public class EnumStringConverter : JsonConverter<Enum>
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsEnum;
    }

    public override Enum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = reader.GetString();
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        if (Enum.TryParse(typeToConvert, value.ToString(), out var result))
        {
            return (Enum)result!;
        }
        throw new InvalidOperationException("值不在枚举范围中");
    }

    public override void Write(Utf8JsonWriter writer, Enum value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(Enum.GetName(value.GetType(), value));
    }
}

然后,定义特性:

[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EnumConverterAttribute : JsonConverterAttribute
{
    public static bool IsNullableType(Type that)
    {
        return !(that == null) && !that.IsArray && that.FullName!.StartsWith("System.Nullable`1[");
    }
    public override JsonConverter CreateConverter(Type typeToConvert)
    {
        return  new EnumStringConverter();
    }
}

使用:

using System.Text.Json;

public enum A
{
    A,
    B,
    C
}

class B
{
    [EnumConverter]
    public A A { get; set; }
}

void Main()
{

    var b = JsonSerializer.Deserialize<B>("{\"A\":\"B\"}");
}

痴者工良

高级程序员劝退师

文章评论