.NET Core: Remove null fields from API JSON response
Asked Answered
A

15

95

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; }
Agential answered 16/6, 2017 at 17:35 Comment(0)
A
184
.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.

Agential answered 16/6, 2017 at 17:35 Comment(8)
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?Jessabell
@Jessabell Hmm, not sure. FWIW, this was for .NET Core 1.0. Perhaps for newer versions there's a better answer you can seek out.Agential
@Jessabell 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.Bolivar
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 thisQuentin
Not sure if it will change but in .NET Core 3 RC1 it is options.JsonSerializerOptions.IgnoreNullValues = true;Anomalous
any idea how we can implement the same in case API returns XML Response using AddXmlSerializerFormattersClearway
If someone is using in .Net 5+ NewtonsoftJson, see my answer belowAlicaalicante
.NET 6 is the same as .NET 5Trunkfish
S
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 
   });
};
Superfuse answered 26/1, 2018 at 13:0 Comment(1)
Is this using Newtonsoft.Json or System.Text.Json? Assuming the former, what's the equivalent for the latter?Bacteriolysis
E
16

I found that for dotnet core 3 this solves it -

services.AddControllers().AddJsonOptions(options => {
     options.JsonSerializerOptions.IgnoreNullValues = true;
});
Eugeniusz answered 23/1, 2020 at 18:16 Comment(2)
please consider elaborating to better explain your answer.Priority
Reference: learn.microsoft.com/en-us/aspnet/core/migration/…Eugeniusz
A
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.

Aleras answered 2/2, 2021 at 9:31 Comment(3)
Thanks for adding this. As you can see, it's quite an old question, with the answer changing as .NET Core evolves.Agential
@Agential yup, it looks like they severely like to change these every single major, lol.Aleras
Respect for the answer! Disrespect to .Net team for the need to search for such things with every release...Matthus
T
10

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; }
Twentyfourmo answered 14/3, 2022 at 15:8 Comment(1)
In .NET 7.0.2 , it is System.Text.Json.Serialization.JsonIgnore .Pang
H
9

.Net core 6 with Minimal API:

using Microsoft.AspNetCore.Http.Json;

builder.Services.Configure<JsonOptions>(options => 
         options.SerializerOptions.DefaultIgnoreCondition 
   = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull);
Hermineherminia answered 11/11, 2021 at 20:55 Comment(0)
A
5

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;
     });
Alicaalicante answered 4/2, 2022 at 0:48 Comment(0)
B
2

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

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });
Bolivar answered 31/10, 2019 at 1:12 Comment(0)
B
2

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

return new JsonResult(result, new JsonSerializerOptions
{
   IgnoreNullValues = true,
});
Buntline answered 7/9, 2020 at 1:25 Comment(0)
T
2

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));
Tjaden answered 16/7, 2023 at 15:22 Comment(0)
G
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;
    });
Geraldina answered 25/11, 2022 at 3:20 Comment(0)
I
1

For .NET 8

 builder.Services.AddControllers()
                .AddJsonOptions(o => o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull);
Interlace answered 27/6, 2023 at 14:50 Comment(1)
Not sure about |, it is not [Flags] enumMaldon
C
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;
            });
Crotchety answered 12/2, 2021 at 12:43 Comment(0)
P
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);
Proven answered 29/5, 2022 at 21:38 Comment(0)
T
-1

The code below work for me in .Net core 2.2

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Triforium answered 11/12, 2019 at 1:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.