首页 新闻 会员 周边

System.Text.Json 反序列化枚举类型的问题

0
悬赏园豆:30 [已解决问题] 解决于 2026-02-27 20:47

请问在 .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
}
dudu的主页 dudu | 高人七级 | 园豆:23423
提问于:2026-02-27 11:41
< >
分享
最佳答案
0

JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

or

JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter<TEnum>());

收获园豆:20
czd890 | 专家六级 |园豆:14787 | 2026-02-27 14:03

通过 JsonStringEnumConverter 可以解决

services.AddControllers()
    .AddJsonOptions(opitons =>
    {
        opitons.JsonSerializerOptions.Converters.Add(
            new JsonStringEnumConverter());
    });

参考:Serializing Enums With System.Text.Json In C# & .NET

dudu | 园豆:23423 (高人七级) | 2026-02-27 15:59

还可以通过 JsonSourceGenerationOptions 实现,参考 How to enable JsonStringEnumConverter for all enums in .NET AOT

dudu | 园豆:23423 (高人七级) | 2026-02-27 16:23
其他回答(1)
0

自己写一个 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)
    {
    }
}
收获园豆:10
flyfishing | 园豆:976 (小虾三级) | 2026-02-27 13:26
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册