Last active
June 13, 2022 11:17
-
-
Save regisdiogo/27f62ef83a804668eb0d9d0f63989e3e to your computer and use it in GitHub Desktop.
ASP.NET Core - Json serializer settings Enum as string and ignore null values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
} | |
} |
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;
});```
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You saved me! Thanks bro!