85

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; }
dotNetkow
  • 5,053
  • 4
  • 35
  • 50

15 Answers15

177
.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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
dotNetkow
  • 5,053
  • 4
  • 35
  • 50
  • 3
    My API returns a complex object which has multiple other complex nodes. Even though there are null/empty values, those keys are seen in response json. Tried this solution but its not working. Will this not work if response json has complex objects? – Aravind Mar 20 '18 at 20:32
  • @Aravind Hmm, not sure. FWIW, this was for .NET Core 1.0. Perhaps for newer versions there's a better answer you can seek out. – dotNetkow Mar 21 '18 at 22:10
  • 1
    @Aravind I was using a error middleware that sets the response format again when an Exceptions occurs, with another json options being setted there. Had to do the same code there too for it to work. Maybe you're using middlewares of settings your JSON configs anywhere other than Startup.cs. It should work exactly as in the answear in all .NET Core versions until now (I'm using latest released 2.2). It should work fine with complex objects too. – Edgar Froes Dec 27 '18 at 03:20
  • 6
    I am facing the a similar scenario, but want to remove Null values for specific given API endpoints in a controller and not all. IS there a way we can do this – Quest Sep 04 '19 at 19:39
  • 1
    Not sure if it will change but in .NET Core 3 RC1 it is options.JsonSerializerOptions.IgnoreNullValues = true; – slopapa Sep 21 '19 at 00:18
  • any idea how we can implement the same in case API returns XML Response using `AddXmlSerializerFormatters` – Posto Mar 11 '20 at 08:48
  • If someone is using in .Net 5+ NewtonsoftJson, see [my answer below](https://stackoverflow.com/questions/44595027/net-core-remove-null-fields-from-api-json-response/70980234#70980234) – Michael Freidgeim Feb 04 '22 at 00:50
  • 1
    .NET 6 is the same as .NET 5 – José Mancharo May 31 '22 at 22:03
26

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 
   });
};
TommyN
  • 2,252
  • 22
  • 19
16

I found that for dotnet core 3 this solves it -

services.AddControllers().AddJsonOptions(options => {
     options.JsonSerializerOptions.IgnoreNullValues = true;
});
Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39
charl botha
  • 169
  • 1
  • 5
  • 1
    please consider elaborating to better explain your answer. – sao Jan 23 '20 at 18:40
  • Reference: https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project – charl botha Jan 26 '20 at 16:28
10

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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
briosheje
  • 7,356
  • 2
  • 32
  • 54
8

.Net core 6 with Minimal API:

using Microsoft.AspNetCore.Http.Json;

builder.Services.Configure<JsonOptions>(options => 
         options.SerializerOptions.DefaultIgnoreCondition 
   = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull);
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Tod
  • 2,070
  • 21
  • 27
4

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;
     });
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
4

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; }
Vy Do
  • 46,709
  • 59
  • 215
  • 313
Adel Tabareh
  • 1,478
  • 14
  • 10
2

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

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });
Edgar Froes
  • 768
  • 8
  • 20
2

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

return new JsonResult(result, new JsonSerializerOptions
{
   IgnoreNullValues = true,
});
yoel halb
  • 12,188
  • 3
  • 57
  • 52
1

Lots of answers, and I've actually used one or two of them in the past but, currently, in DOTNET 7+ (probably 6 too) it is as simple as the Minimal API Tutorial's section Configure JSON Serialization Options shows. Just use Builder.Services.ConfigureHttpJsonOptions() as per the excerpt below:

var builder = WebApplication.CreateBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options => {
    options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    // set other desired options here...
    options.SerializerOptions.WriteIndented = true;
    options.SerializerOptions.IncludeFields = true;
});

var app = builder.Build();

Now you can also easily (see the tutorial for more information) add options per endpoint as bellow:

// creates a JsonSerializerOptions object with default "Web" options
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
    { WriteIndented = true };

// pass it to the endpoint mapping 
app.MapGet("/", () => 
    Results.Json(new Todo { Name = "Walk dog", IsComplete = false }, options));
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Loudenvier
  • 8,362
  • 6
  • 45
  • 66
0

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;
            });
Satheesh K
  • 67
  • 9
0

One more way in .Net 6, for specific ObjectResult:

public class IdentityErrorResult : BadRequestObjectResult
{
    public IdentityErrorResult([ActionResultObjectValue] object? error) : base(error)
    {
        Formatters.Add(new SystemTextJsonOutputFormatter(new JsonSerializerOptions
        {
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
        }));
    }
}

in Controller:

public IdentityErrorResult IdentityError(ErrorResponseObject value)
  => new IdentityErrorResult(value);
Alex Buchatski
  • 180
  • 2
  • 7
0

If you are using .NET 6 and want to get rid of the null values in your REST response, on Program.cs just add the following lines:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
Felipe La Rotta
  • 343
  • 3
  • 13
0

For .NET 8

 builder.Services.AddControllers()
                .AddJsonOptions(o => o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull);
tonycdp
  • 137
  • 2
  • 9
-1

The code below work for me in .Net core 2.2

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
zmag
  • 7,825
  • 12
  • 32
  • 42