Json – Ignore property when null using the new Net Core 3.0 Json

.net-core-3.0asp.net-core-3.0jsonjson.netsystem.text.json

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?

Best Answer

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

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

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