ASP.NET MVC Core 3.0 API Serialize Enums to String

2020-06-08 15:11发布

How to serialize Enum fields to String instead of an Int in ASP.NET MVC Core 3.0? I'm not able to do it the old way.

services.AddMvc().AddJsonOptions(opts =>
{
    opts.JsonSerializerOptions.Converters.Add(new StringEnumConverter());
})

I'm getting an error:

cannot convert from 'Newtonsoft.Json.Converters.StringEnumConverter' to 'System.Text.Json.Serialization.JsonConverter'

1条回答
Fickle 薄情
2楼-- · 2020-06-08 15:35

New System.Text.Json serialization

ASP.NET MVC Core 3.0 uses built-in JSON serialization. Use System.Text.Json.Serialization.JsonStringEnumConverter (with "Json" prefix):

services
    .AddMvc()
    // Or .AddControllers(...)
    .AddJsonOptions(opts =>
    {
        opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    })

More info here. The documentation can be found here.

If you prefer Newtonsoft.Json

You can also use "traditional" Newtonsoft.Json serialization:

services
    .AddControllers()
    .AddNewtonsoftJson(opts => opts.Converters.Add(new StringEnumConverter()));
查看更多
登录 后发表回答