.NET Core: Remove null fields from API JSON response

JsonSerialization.Net Coreasp.net Core-1.0

Json Problem Overview


On a global level in .NET Core 1.0 (all API responses), how can I configure Startup.cs so that null fields are removed/ignored in JSON responses?

Using Newtonsoft.Json, you can apply the following attribute to a property, but I'd like to avoid having to add it to every single one:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FieldName { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string OtherName { get; set; }

Json Solutions


Solution 1 - Json

.NET Core 1.0

In Startup.cs, you can attach JsonOptions to the service collection and set various configurations, including removing null values, there:

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc()
             .AddJsonOptions(options => {       
                  options.SerializerSettings
                         .NullValueHandling = NullValueHandling.Ignore;
     });
}
.NET Core 3.1

Instead of this line:

options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

Use:

options.JsonSerializerOptions.IgnoreNullValues = true;
.NET 5.0

Instead of both variants above, use:

 options.JsonSerializerOptions.DefaultIgnoreCondition 
                       = JsonIgnoreCondition.WhenWritingNull;

The variant from .NET Core 3.1 still works, but it is marked as NonBrowsable (so you never get the IntelliSense hint about this parameter), so it is very likely that it is going to be obsoleted at some point.

Solution 2 - Json

This can also be done per controller in case you don't want to modify the global behavior:

public IActionResult GetSomething()
{
   var myObject = GetMyObject();
   return new JsonResult(myObject, new JsonSerializerSettings() 
   { 
       NullValueHandling = NullValueHandling.Ignore 
   });
};

Solution 3 - Json

I found that for dotnet core 3 this solves it -

services.AddControllers().AddJsonOptions(options => {
     options.JsonSerializerOptions.IgnoreNullValues = true;
});

Solution 4 - Json

In net 5, it's actually DefaultIgnoreCondition:

public void ConfigureServices(IServiceCollection services)
{
   services.AddControllers()
           .AddJsonOptions(options =>
                {
 options.JsonSerializerOptions.DefaultIgnoreCondition =
        System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
                });
        }

This will prevent both serializazion and deserialization of any null value without needing any extra attribute on properties.

Solution 5 - Json

The following works for .NET Core 3.0, in Startup.cs > ConfigureServices():

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });

Solution 6 - Json

In .Net 5 and greater, if you are using AddNewtonsoftJson instead of AddJsonOptions, the setting is as following

 services.AddMvc(options =>
                    {
                       //any other settings
                    })
                    .AddNewtonsoftJson(options =>
                    {
                        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                    });

Solution 7 - Json

If you would like to apply this for specific properties and only use System.Text.Json then you can decorate properties like this

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string Market { get; set; }

Solution 8 - Json

In Asp.Net Core you can also do it in the action method, by returning

return new JsonResult(result, new JsonSerializerOptions
{
   IgnoreNullValues = true,
});

Solution 9 - Json

.Net core 6 with Minimal API:

using Microsoft.AspNetCore.Http.Json;

builder.Services.Configure<JsonOptions>(options => 
         options.SerializerOptions.DefaultIgnoreCondition 
   = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull);

Solution 10 - Json

I used the below in my .net core v3.1 MVC api.

 services.AddMvc().AddJsonOptions(options =>
            {

                options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
            });

Solution 11 - Json

The code below work for me in .Net core 2.2

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondotNetkowView Question on Stackoverflow
Solution 1 - JsondotNetkowView Answer on Stackoverflow
Solution 2 - JsonTommyNView Answer on Stackoverflow
Solution 3 - Jsoncharl bothaView Answer on Stackoverflow
Solution 4 - JsonbrioshejeView Answer on Stackoverflow
Solution 5 - JsonEdgar FroesView Answer on Stackoverflow
Solution 6 - JsonMichael FreidgeimView Answer on Stackoverflow
Solution 7 - JsonAdel TabarehView Answer on Stackoverflow
Solution 8 - Jsonyoel halbView Answer on Stackoverflow
Solution 9 - JsonTodView Answer on Stackoverflow
Solution 10 - JsonSatheesh KView Answer on Stackoverflow
Solution 11 - JsonGlenox AndalView Answer on Stackoverflow