Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Core API Serialize Enums to String

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'

like image 237
Andrei Avatar asked Nov 28 '19 21:11

Andrei


People also ask

Can JSON serialize enums?

Using @JsonValue. We've learned how to use @JsonValue to serialize Enums. We can use the same annotation for deserialization as well. This is possible because Enum values are constants.

Are enums serializable C#?

In C#, enums are backed by an integer. Most tools will serialize or save your enums using that integer value.

How do you convert a string value to a specific enum type in C#?

TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .


2 Answers

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()));
like image 59
Andrei Avatar answered Oct 17 '22 00:10

Andrei


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

like image 21
J. Liu Avatar answered Oct 17 '22 02:10

J. Liu