内容目录
定义转换器:
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\"}");
}
文章评论