请问在 .NET 10 中如何让 System.Text.Json 反序列化 enum 类型时既支持数字又支持字符串?
比如下面的枚举类型 FeedListType
public enum FeedListType
{
Concern = 1,
Friend = 2,
Follow = 3,
Me = 4,
All = 5
}
作为 FeedQuery 类的属性
public class FeedQuery
{
public FeedListType? FeedListType { get; set; }
}
在 web api Action 中被使用
[Route("recent"), HttpPost]
public async Task<PagedResult<FeedDto>> GetRecentFeeds(FeedQuery feedQuery)
{
// ...
}
如果请求时 json 中使用数字作为枚举值
{
"FeedListType": 5
}
asp.net core web api 在反序列化时会报错
JSON input formatter threw an exception: "The JSON value could not be converted to System.Nullable`1[Cnblogs.Feed.FeedListType]. Path: $.feedListType | LineNumber: 0 | BytePositionInLine: 312."
如果改为使用字符串作为枚举值,就可以正常反序列化
{
"FeedListType": All
}
JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
or
JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter<TEnum>());
通过 JsonStringEnumConverter 可以解决
services.AddControllers()
.AddJsonOptions(opitons =>
{
opitons.JsonSerializerOptions.Converters.Add(
new JsonStringEnumConverter());
});
还可以通过 JsonSourceGenerationOptions 实现,参考 How to enable JsonStringEnumConverter for all enums in .NET AOT
自己写一个 EnumConverter ?
public class EnumConverter : JsonConverter<int?>
{
public override Enum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
}
public override void Write(Utf8JsonWriter writer, Enum value, JsonSerializerOptions options)
{
}
}