Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core: Remove null fields from API JSON response

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; } 
like image 659
dotNetkow Avatar asked Jun 16 '17 17:06

dotNetkow


People also ask

Should JSON include null values?

You should definitely include it if there is any need to distinguish between null and undefined since those have two different meanings in Javascript. You can think of null as meaning the property is unknown or meaningless, and undefined as meaning the property doesn't exist.


1 Answers

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

like image 134
dotNetkow Avatar answered Sep 21 '22 03:09

dotNetkow