Overview
ℹ️ Important
Availability: C# 11 / .NET 7
Properties can be marked required
to indicate that they must be present in the JSON payload for deserialization to succeed. Otherwise, Deserialize
methods throw a JsonException.
Techniques for Marking Fields/Properties
- Add the
required
modifier to the field/property (C# 11) - Annotate the property with
JsonRequiredAttribute
(.NET 7) a. Use this technique if the requirement should only apply to deserialization. - Modify the
JsonPropertyInfo.IsRequired
property of the contract model (.NET 7)
Example
public class Person
{
public required string Name { get; set; }
public int Age { get; set; }
}
or:
[JsonRequired]
public string Name { get; set; }