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