ASP.NET MVC Core API Serialize Enums to String

C#asp.net Mvcasp.net Core-3.0.Net Core-3.0system.text.json

C# Problem Overview


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'

C# Solutions


Solution 1 - C#

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 =>
    {
        var enumConverter = new JsonStringEnumConverter();
        opts.JsonSerializerOptions.Converters.Add(enumConverter);
    })

More info here. The documentation can be found here.

If you prefer Newtonsoft.Json

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

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

And then:

services
    .AddControllers()
    .AddNewtonsoftJson(opts => opts
        .Converters.Add(new StringEnumConverter()));

Solution 2 - C#

some addition:
if use Newtonsoft.Json

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
services
    .AddControllers()
    .AddNewtonsoftJson(options =>
        options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()));

options.SerializerSettings.Converters

SerializerSettings is necessary

Solution 3 - C#

If you have a Minimal API this will be useful:

using System.Text.Json.Serialization;

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opt =>
{
    opt.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

Solution 4 - C#

If you are using Aspnet Core MVC with the minimal API use this:

        services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(o => o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreiView Question on Stackoverflow
Solution 1 - C#AndreiView Answer on Stackoverflow
Solution 2 - C#J. LiuView Answer on Stackoverflow
Solution 3 - C#giorgi02View Answer on Stackoverflow
Solution 4 - C#Michael EdwardsView Answer on Stackoverflow