'ASP.NET Core - JsonSerializerOptions.DefaultIgnoreCondition not working for IEnumerable<T>

I've one ASP.NET web app running over .NET Core 3.1 into one AWS Lambda;

On Startup.cs I had this configuration:

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

After update the package "Amazon.Lambda.AspNetCoreServer" to the version "7.1.0", ASP.NET version and System.Text.Json was updated together.

Everything continues running ok, but the JsonSerializerOptions API changes and property "IgnoreNullValues" keeps obsolete. The link below suggests changes the configuration to use property "DefaultIgnoreCondition":

https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.ignorenullvalues?view=net-6.0

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

But after it, properties with type IEnumerable returns after serialization even when the property has a null value;

My question is: How to keep the behavior to not include the property when is null, even to IEnumerable<> properties?

I need don't change the behavior of the Web API consumed for some Delphi desktop app that breaks when receive null to lists.

Observation: I notice that the behavior occur in System.Text.Json from version 6.x.x



Solution 1:[1]

Maybe somebody can use the repository to reproduce.

After my test, this scenario only happend on ASP.NET CORE 3.1 + System.Text.Json 6 + set DefaultIgnoreCondition + return ObjectResult().

And just like @Gean Ribeiro's talk, if you use IgnoreNullValues and ignore the obsolete warning, everything can run ok.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bnet