Adam Wojnar
Adam Wojnar

Reputation: 545

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

Upvotes: 4

Views: 3499

Answers (1)

Trevi Awater
Trevi Awater

Reputation: 2407

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

Upvotes: 2

Related Questions