3

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

Adam Wojnar
  • 473
  • 6
  • 19
  • There is another good answer on a similar question: https://stackoverflow.com/questions/59096102/asp-net-mvc-core-3-0-api-serialize-enums-to-string – Tobias Feb 27 '20 at 15:27

1 Answers1

2

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()));
Trevi Awater
  • 2,387
  • 2
  • 31
  • 53