Skip to content

Implement a concept of "Required" properties #29861

@ryanbrandenburg

Description

@ryanbrandenburg

AB#1130869

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.

Metadata

Metadata

Assignees

Labels

Cost:MWork that requires one engineer up to 2 weeksPriority:1Work that is critical for the release, but we could probably ship withoutTeam:LibrariesUser StoryA single user-facing feature. Can be grouped under an epic.api-approvedAPI was approved in API review, it can be implementedarea-System.Text.JsonblockingMarks issues that we want to fast track in order to unblock other important workenhancementProduct code improvement that does NOT require public API changes/additionsjson-functionality-docMissing JSON specific functionality that needs documenting

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions