Andy Dobedoe
Andy Dobedoe

Reputation: 747

.NET Core 3.0 StringEnumConverter not serializing as string

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.

Upvotes: 14

Views: 20599

Answers (5)

delepster
delepster

Reputation: 179

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

using Microsoft.AspNetCore.Mvc;
    
builder.Services.AddMvc()
    .AddNewtonsoftJson();

More details at Newtonsoft.Json support

Upvotes: 17

Laurent F
Laurent F

Reputation: 21

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

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

Upvotes: 0

Ngo Quoc
Ngo Quoc

Reputation: 271

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

Upvotes: 27

Ahmed Msaouri
Ahmed Msaouri

Reputation: 316

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;

Upvotes: 0

Andy Dobedoe
Andy Dobedoe

Reputation: 747

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;

Upvotes: 25

Related Questions