ASP.NET MVC Core 3.0 API Serialize Enums to String

会有一股神秘感。 提交于 2020-03-18 04:28:07

问题


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:


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().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()));


来源:https://stackoverflow.com/questions/59096102/asp-net-mvc-core-3-0-api-serialize-enums-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!