-
-
Save regisdiogo/27f62ef83a804668eb0d9d0f63989e3e to your computer and use it in GitHub Desktop.
public class Startup | |
{ | |
public IServiceProvider ConfigureServices(IServiceCollection services) | |
{ | |
services.AddMvc().AddJsonOptions(options => | |
{ | |
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); | |
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; | |
}); | |
} | |
} |
Seems to not be working for enums in response.
Limitation here: There doesn't seem to be a way to simply allow strings as enums but still prefer integers. I want to still allow input JSON bodies to accept strings for enums but dont want to serialize results with strings
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
2021.. still rocks! )
YOU SAVED MEEE BRRRROOOOOO
You saved me! Thanks bro!
Didn't work for me. I ended up adding a schema filter and then...
You saved me! Thanks bro!
You saved me! many thanks bro.
You saved me! Thanks bro!
You saved me! Thanks bro!
Maybe this would help somebody. The same code for .net core 3.0 will look like this:
services.AddMvc() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.IgnoreNullValues = true; });
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
Nice!
using System.Text.Json.Serialization;
...
services
.AddControllers()
.AddNewtonsoftJson()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.IgnoreNullValues = true;
});
Working in .NET core 5.0
Make sure to include AddNewtonsoftJson()
if you're using JSON PATCH. Otherwise it wont work.
Nice!
using System.Text.Json.Serialization; ... services .AddControllers() .AddNewtonsoftJson() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.IgnoreNullValues = true; });
Working in .NET core 5.0
Make sure to include
AddNewtonsoftJson()
if you're using JSON PATCH. Otherwise it wont work.
thank you!
You saved me! Thanks bro!
Saving bros since 2018.
You saved me for the 3rd time! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro!
You saved me! Thanks bro! 🤣
You saved me! Thanks bro!
You saved me! Thanks bro!
For dotnet 6 a few options were deprecated
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
// serialize enums as strings in api responses (e.g. Role)
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
// ignore omitted parameters on models to enable optional params (e.g. User update)
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});```
You saved me! Thanks bro!