Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize enum as string globally (not by attribute in each enum)?

I'm working on the ASP.NET Core 3.0 web API. A lot of endpoints return json with enums. Enums are not serialized as a string but as the default integer.

I'm aware of [JsonConverter(typeof(StringEnumConverter))] attribute. But I'm looking for a solution, where I would globally say "Every enum returned by this API should be serialized to string, without the need of manually declaring attributes in my model in each and every enum".

Until today, I worked with .NETCore2.1. I was able to achieve that with Newtonsoft.Json.Converters and this middleware:

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(op => { op.SerializerSettings.Converters.Add(new StringEnumConverter());});

This code doesn't work in .NETCore3.0, so I'm looking for a solution that will globally convert enum to string, always, without changing or decorating my model classes in NETCore3.0.

Thanks for help

like image 676
Adam Wojnar Avatar asked Oct 19 '25 15:10

Adam Wojnar


1 Answers

In .NET Core 3.0, the Newtonsoft.JSON package is no longer included by default.

Install the following package and try to add the converter like this:

services.AddMvc(...).AddNewtonsoftJson(opt => SerializerSettings.Converters.Add(new StringEnumConverter()));
like image 188
Trevi Awater Avatar answered Oct 21 '25 04:10

Trevi Awater