14

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 5

27

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

Sign up to request clarification or add additional context in comments.

Comments

25

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;

2 Comments

Note, someone trying to answer this would never have guessed this, which is why it's very important to provide a Minimal, Reproducible code sample in your question.
Yes, I also faced this issue. Thank you for your answer.
17

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

1 Comment

All the above answers are right and for ASP.NET Core 3.0 and above this is the Silver Bullet! Thanks @delepster.
0

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;

Comments

-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.