59

When using JSON.Net in ASP.Net Core 2.2 I was able to ignore a property when its value was null when serializing to JSON:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? Created { get; set; }

But when using the new ASP.Net Core 3.0 built in JSON (System.Text.Json) I can’t find an equivalent attribute to ignore a property if its value is null.

I could only find JsonIgnore.

Am I missing something?

dbc
  • 104,963
  • 20
  • 228
  • 340
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • 4
    There is a thread on the [corefx github](https://github.com/dotnet/corefx/issues/40600) suggesting this get implemented but it looks like it's an all or nothing thing at the moment using `JsonSerializerOptions.IgnoreNullValues` – Simply Ged Sep 26 '19 at 04:47
  • System.Text.Json is meant for simple scenarios for now. It's main focus is speed and low allocations. You may have to use custom formatters or use JSON.NET fro more advanced scenarios – Panagiotis Kanavos Sep 26 '19 at 07:19
  • @PanagiotisKanavos Are you talking about JsonConverter? I have been looking for an example of how to do this but I can't find any ... – Miguel Moura Sep 26 '19 at 13:50
  • @SimplyGed Any idea how to accomplish this for now using System.Text.Json even if extra code is needed? – Miguel Moura Sep 26 '19 at 13:51
  • If you check the answers at this question of mine, they have some clever solutions using `JsonDocumnet` and `Utf8JsonReader` in `System.Text.Json`: https://stackoverflow.com/questions/56835040/net-core-3-0-jsonserializer-populate-existing-object – Asons Sep 27 '19 at 12:20
  • @LGSon Sorry, not sure how can I solve my problem with your suggestion. I would prefer to define a custom converter for a class of type Envelope where the property created is. But I am not sure how. – Miguel Moura Sep 27 '19 at 19:58
  • Me neither, just wanted to share what they did. There could have been something. – Asons Sep 27 '19 at 20:06
  • 1
    Does this answer your question? [.NET Core: Remove null fields from API JSON response](https://stackoverflow.com/questions/44595027/net-core-remove-null-fields-from-api-json-response) – Michael Freidgeim Feb 21 '20 at 12:14

10 Answers10

57

I'm looking at .Net Core 3.1, where this should ignore null values

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

While in .NET 5 and later, set JsonSerializerOptions.DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull:

services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

Note, the above isn't per property/attribute, although there is an attribute which may be helpful JsonIgnoreAttribute.

An alternative, to solve your problem might be a JsonConverterAttribute, information on how to write your own converter is here

dbc
  • 104,963
  • 20
  • 228
  • 340
0909EM
  • 4,761
  • 3
  • 29
  • 40
47

This was fixed on .Net 5

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]

See the updates below

https://github.com/dotnet/runtime/issues/41313

https://github.com/dotnet/runtime/issues/30687

Murilo Maciel Curti
  • 2,677
  • 1
  • 21
  • 26
13

If you want property level control of ignoring null values during JSON serialization, for Net Core 3.1 you'll have to write a custom converter. There are examples described in the Newtonsoft.Json migration documentation.

That is a big hassle for functionality that was declarative using Newtonsoft.Json. You can specify to use Newtonsoft.Json by specifying as much in Startup.ConfigureServices().

services.AddControllers()
    .AddNewtonsoftJson();

As the documentation notes, you'll need to add the Microsoft.AspNetCore.Mvc.NewtonsoftJson package.

dblood
  • 1,758
  • 17
  • 21
  • 1
    this answer is most likely the one everyone is after. As IgnoreNullValues only seems to apply to deserialization of an entry object. If you, like me, want to keep the same contracts for requests and response, adding newtonsoft back was the only option. For instance my returned objects would ommit any field that was nullable, which unfortunately would break the "unofficial" contracts we had. – rjso Nov 02 '20 at 13:48
10

Adding this to your startup should help although it's not per property and it's not an attribute.

services.AddMvc()
        .AddJsonOptions(options =>{ options.JsonSerializerOptions.IgnoreNullValues = true; });
Moriya
  • 7,750
  • 3
  • 35
  • 53
9

If you are still using Newtonsoft.Json in .net core 3.1, you want to have configuration like below.

services
   .AddControllers()
   .AddJsonOptions(options =>
   {
       options.JsonSerializerOptions.IgnoreNullValues = true;
   })
   .AddNewtonsoftJson(options =>
   {
       options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
   });
cdev
  • 5,043
  • 2
  • 33
  • 32
  • 2
    At least for .NET Core 3.1, no need to call AddJsonOptions, but just: ```.AddNewtonsoftJson(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; });``` – kotpal Jul 22 '20 at 01:21
  • 1
    If you are using system.text.json then you need. – cdev Jul 22 '20 at 06:16
3

If you are using System.Text.Json (.net 5.0) and you want to ignore all null use WhenWritingNull condition:

services.AddControllers().AddJsonOptions(a =>
     {
        a.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;            
        a.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
     });
Daniel
  • 2,780
  • 23
  • 21
1

For Minimal APIs running in DOTNET 7+ (probably 6 too) you can configure it globally simply as the Minimal API Tutorial's section Configure JSON Serialization Options shows. Just use Builder.Services.ConfigureHttpJsonOptions() as per the excerpt bellow:

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();
Loudenvier
  • 8,362
  • 6
  • 45
  • 66
0

TL&DR: In DotNet 6 NullValueHandling has been deprecated. Instead, use DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull

   services.AddControllersWithViews().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
     
        });
FlyingV
  • 2,207
  • 19
  • 18
0

If your using .Net core 6 and System.Text.Json, then add this change in program.cs

services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

// if you want to remove $Id (metadata) from the response, add the below line
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
Shareef
  • 11
  • 1
-3

See the official migration guide Migrate from ASP.NET Core 2.2 to 3.0

Your service codes should look like this:

services.AddMvc(c =>
{

})
.AddNewtonsoftJson(
    options =>
        {
            options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            options.SerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;                      

            options.SerializerSettings.Error = (object sender, ErrorEventArgs args) =>
            {
               // handle error
            };
        }
    );
wonea
  • 4,783
  • 17
  • 86
  • 139
Recep Yesil
  • 148
  • 13
  • 1
    If you want property level control on ignoring null values and you don't want to go through the rather large hassle of writing custom converters then using Newtonsoft.Json is a valid approach. – dblood May 21 '20 at 16:36