首页 问答 System.Text.Json 反序列化枚举类型的问题
问题详情

请问在 .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

发表评论
暂无评论

还没有评论呢,快来抢沙发~

点击联系客服

在线时间:8:00-16:00

客服QQ

70068002

客服电话

400-888-8888

客服邮箱

70068002@qq.com

扫描二维码

关注微信公众号

扫描二维码

手机访问本站