问题详情
请问在 .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>());
版权:言论仅代表个人观点,不代表官方立场。转载请注明出处:https://www.stntk.com/question/2528.html
还没有评论呢,快来抢沙发~