-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JsonIgnoreCondition.WhenWritingNull doesn't play well with required nullable properties #76527
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsI'm not sure if this is intentional or not, but I'm experiencing an issue when trying to use required nullable properties in my API DTOs.
Combining these points lead to an exception upon deserializing a serialized object whose nullable required property was set to null. I would expect deserialization to ignore required nullable properties when Minimal reproductionCode:
Exception:
|
This is by design -- not setting a The reason you're seeing this error message is that the two configurations are mutually contradictory: it's not possible to roundtrip a value when it's both ignored on serialization and required on deserialization. Suggested workaround would be to override the ignore condition for the specific properties that are marked public class Foo
{
[JsonIgnore(JsonIgnoreCondition.Never)]
public required string? Bar { get; set; }
} |
Maybe this issue should be changed into a feature request then. The deserializer could be changed so that if a required property is missing, but I don't think your workaround is valid as I want to ignore the property when serializing if is it null |
You should be able to use contract customization to switch off required properties in the context of JSON deserialization. But I wouldn't recommend this approach: by turning off deserialization validation for |
A new value for I don't think my use case is unreasonable. I want to the What about an option in Option 1: Make |
As mentioned, this is already possible using the contract model. |
Closing as answered. |
.NET SDK: 7.0.100-rc.1.22431.12
I'm not sure if this is intentional or not, but I'm experiencing an issue when trying to use required nullable properties in my API DTOs.
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
.Combining these points lead to an exception upon deserializing a serialized object whose nullable required property was set to null.
I would expect deserialization to ignore required nullable properties when
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
Minimal reproduction
Code:
Exception:
The text was updated successfully, but these errors were encountered: