Andrei
Andrei

Reputation: 44590

ASP.NET Core MVC API : serialize enums to string

How to serialize Enum fields to String instead of an Int in ASP.NET Core 3.0 MVC? 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'

Upvotes: 106

Views: 73414

Answers (5)

asaf92
asaf92

Reputation: 1855

.NET 7.0 introduces this way:

builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));

Upvotes: 19

Michael Edwards
Michael Edwards

Reputation: 6518

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

Upvotes: 3

giorgi02
giorgi02

Reputation: 1043

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

Upvotes: 28

Andrei
Andrei

Reputation: 44590

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

Upvotes: 213

J. Liu
J. Liu

Reputation: 366

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

Upvotes: 28

Related Questions