-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
Background and motivation
My team stumbled on the similar issue which is described here 106392, discussion under this issue is pretty lengthy so I won't be repeating every detail. What we want to achieve basically is to use nullability in our API contracts to express both the fact that certain parameter accepts null as a valid value and that it is optional (client should be able to omit it in his JSON request). Opposite is also true if the parameter is not marked as nullable, null value is not valid and it is required (can't be omitted in JSON request). By nullable parameters I mean both value types wrapped in Nullable<T> and reference types annotated with ?.
It means that deserializing below class from empty JSON ({}) should succeed.
public class User
{
public string? Name { get; }
public User(string? name)
{
Name = name;
}
}and below should fail
public class User
{
public string Name { get; }
public User(string name)
{
Name = name;
}
}Based on what we can read here I understand that you don't want to fix the bug in RespectNullableAnnotations setting due to breaking change, even though this behavior may be misleading to many (to how many it is hard to know because this issue was closed so it can't be upvoted). In that context is it possible to add new setting TreatNullableConstructorParametersAsOptional which we would be able to use in combination with existing settings (RespectNullableAnnotations and RespectRequiredConstructorParameters) to achieve desired behavior?
API Proposal
new JsonSerializerOptions
{
RespectNullableAnnotations = true,
RespectRequiredConstructorParameters = true,
TreatNullableConstructorParametersAsOptional = true //new setting
}Alternative Designs
No response
Risks
No response