ASP.NET MVC Core API Serialize Enums to String
Solution 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()
// 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
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
Andrei
There are 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors. .NET, Azure, ASP.NET MVC, JavaScript, React-Native
Updated on July 05, 2022Comments
-
Andrei almost 2 years
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'
-
Tobias about 4 yearsIf you have a Web API then instead of
.AddMvc()
you can also useservices.AddControllers().AddJsonOptions(...)
. -
Sudhanshu Mishra almost 4 yearsas of asp.net core 3.1 and Microsoft.AspNetCore.Mvc.NewtonsoftJson 3.1.5, there is a slight change: <pre> services.AddControllers() .AddNewtonsoftJson(opts => opts.SerializerSettings.Converters.Add(new StringEnumConverter())); </pre>
-
drowhunter over 3 yearswhat if i dont want to do this accross the bard ? is there a way to do this as an attribute on my dto?
-
ashlar64 over 3 yearsI found this website to be very helpful: jasongaylord.com/blog/2020/07/17/…
-
Gavin almost 3 years@drowhunter If you want to just do this or a specific property, you can simply annotate the property in the return DTO like this
[JsonConverter(typeof(JsonStringEnumConverter))] public CategoryDto Category { get; set; }
. You will need to import theusing System.Text.Json.Serialization
namespace -
Qwerty almost 3 yearsThank you this worked for me
services.AddControllers()..AddJsonOptions(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); })