.NET Core 3.0 StringEnumConverter not serializing as string

Viewed 16017

When decorating your enum with:

[JsonConverter(typeof(StringEnumConverter))]
public EventEntity Entity { get; set; }

And serializing it with JsonConvert.SerializeObject(myEvent)

You may notice that the enum is not serialized as a string but as the default integer.

5 Answers

Simple one really but had me scratching my head for 20 mins or so...

When using the JsonConverter atribute, the first intellisense import is: using System.Text.Json.Serialization

But you should instead use: using Newtonsoft.Json;

If you are using plain System.Text.Json without Newtonsoft.JSON, this snippet in Startup.cs might help:

// using System.Text.Json.Serialization
services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        });

The key takeaway here is the this converter defined in System.Text.Json (notice the class name is different from the one from Newtonsoft.JSON): JsonStringEnumConverter

Make sure to add the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package, and call .AddNewtonsoft() in Startup ConfigureServices(IServiceCollection services) method right after services.AddMvc(...). If you do not, everything compiles fine, seems to run, but in fact, nothing works properly.

More details here

You have to install the Newtonsoft.Json libraries, find the latest version in the NuGet package manager, and add it to the project

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

In System.Text.Json, you can use JsonStringEnumConverter to replace Newtonsoft.Json.Converters.StringEnumConverter.

services.AddMvc().AddJsonOptions(options =>
{
   options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

Related