99

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; }

15 Answers 15

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

Sign up to request clarification or add additional context in comments.

8 Comments

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 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.
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
Not sure if it will change but in .NET Core 3 RC1 it is options.JsonSerializerOptions.IgnoreNullValues = true;
.NET 6 is the same as .NET 5
|
30

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 
   });
};

1 Comment

Is this using Newtonsoft.Json or System.Text.Json? Assuming the former, what's the equivalent for the latter?
17

I found that for dotnet core 3 this solves it -

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

2 Comments

please consider elaborating to better explain your answer.
15

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; }

1 Comment

In .NET 7.0.2 , it is System.Text.Json.Serialization.JsonIgnore .
12

.Net core 6 with Minimal API:

using Microsoft.AspNetCore.Http.Json;

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

Comments

11

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.

3 Comments

Thanks for adding this. As you can see, it's quite an old question, with the answer changing as .NET Core evolves.
@dotNetkow yup, it looks like they severely like to change these every single major, lol.
Respect for the answer! Disrespect to .Net team for the need to search for such things with every release...
6

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;
     });

Comments

3

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));

Comments

2

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

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

Comments

2

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

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

Comments

1

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;
    });

Comments

1

For .NET 8

 builder.Services.AddControllers()
                .AddJsonOptions(o => o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull);

1 Comment

Not sure about |, it is not [Flags] enum
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;
            });

Comments

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);

Comments

-1

The code below work for me in .Net core 2.2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.