0

I am trying to move from Json.Net to system.Text.Json library in .Net core 3.1. I notice an odd behavior, that swagger doesn't show the attribute that have [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] on the request UI. system.Text.Json

The request class :

public class AdvancedSearch 
{
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
        public int? StatusID { get; set; }

        public int? SessionCode { get; set; }

        public int? KeywordVersionID { get; set; }
}

Swagger UI : enter image description here

Json.Net The request class :

public class AdvancedSearch 
    {
            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public int? StatusID { get; set; }
    
            public int? SessionCode { get; set; }
    
            public int? KeywordVersionID { get; set; }
    }

Swagger UI : enter image description here

newtonsoft works as it supposed to, serialize/deserialize while ignoring null values, but still showing them on swagger UI.

Is there a way to have System.Text.Json do the same ?

Rena
  • 30,832
  • 6
  • 37
  • 72
Ayoub Salhi
  • 312
  • 1
  • 4
  • 19
  • [`JsonIgnoreAttribute.Condition`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonignoreattribute.condition?view=net-5.0) was introduced in .NET 5. It's not available in [.NET Core 3.1](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonignoreattribute.condition?view=net-5.0&viewFallbackFrom=netcore-3.1). Are you sure you are not using a version of swagger intended for .NET Core 3.1 (which won't know about `JsonIgnoreCondition.WhenWritingNull`) with .NET 5? Or mixing up versions in some other way perhaps? – dbc Aug 19 '21 at 16:56
  • What are the exact names and versions of the framework and optional nuget(s) you are using? – dbc Aug 19 '21 at 17:00
  • "Swashbuckle.AspNetCore" Version="6.1.4" "Swashbuckle.AspNetCore.Annotations" Version="6.1.4" "Swashbuckle.AspNetCore.Filters" Version="7.0.2" – Ayoub Salhi Aug 19 '21 at 17:03
  • Just downgraded to "Swashbuckle.AspNetCore" Version="5.46.1.4" & "Swashbuckle.AspNetCore.Annotations" Version="5.4.1" .. but problem persists. – Ayoub Salhi Aug 19 '21 at 17:04
  • 1
    Downgrading won't help, it would be better to use the latest versions as they are more likely to have full .NET 5 support. But it looks to be a known bug, see [JsonIgnoreCondition is not respected #1899](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1899). – dbc Aug 19 '21 at 17:36

0 Answers0