-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
API proposal:
namespace System.Text.Json.Serialization
{
[AttributeTargets.Field | AttributeTargets.Property, AllowMultiple=false)]
public sealed class JsonRequiredAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonRequiredAttribute() {}
}
}
namespace System.Text.Json.Serialization.Metadata
{
public abstract partial class JsonPropertyInfo
{
public bool IsRequired { get; set; }
}
}Current situation
There's no way to indicate that if an object doesn't have a particular property that serialization should fail.
For example:
public class Person
{
[JsonRequired]
public string Name { get; set; }
public int Age { get; set; }
}{
"Age": 46
}Trying to deserialize the above json as a Person will succeed, even though it's been indicated that the name attribute is required, and is missing.
Describe the solution you'd like
System.Text.Json should respect either System.ComponentModel.DataAnnotations.RequiredAttribute or a new attribute (likely extending System.Text.Json.JsonAttribute) and error when an attempt is made to serialize an object which doesn't have that property.
Describe alternatives you've considered
Using System.ComponentModel.DataAnnotations.RequiredAttribute might be troublesome because it could indicate Requirement in a different context. The alternative is that users implement their own "Required" functionality (and likely get it wrong or incomplete).
CC @pranavkm who I talked about this with.