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'
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.
In C#, enums are backed by an integer. Most tools will serialize or save your enums using that integer value.
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 .
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.
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()));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With