Suppress properties with null value on ASP.NET Web API
In the WebApiConfig
:
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
Or, if you want more control, you can replace entire formatter:
var jsonformatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
NullValueHandling = NullValueHandling.Ignore
}
};
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);
For ASP.NET Core 3.0, the ConfigureServices()
method in Startup.cs
code should contain:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
I ended up with this piece of code in the startup.cs file using ASP.NET5 1.0.0-beta7
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});