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!
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!