Json.NET require all properties on deserialization

If your model has properties that your JSON may omit, and you want that to be an error, add the attribute [JsonObject(ItemRequired=Required.Always)] to your classes:

Type: Required

A value indicating whether the object’s properties are required.

Possible values for Required are:

  • Default: The property is not required. The default state.
  • AllowNull: The property must be defined in JSON but can be a null value.
  • Always: The property must be defined in JSON and cannot be a null value.
  • DisallowNull: The property is not required but it cannot be a null value [if present]. (Json.NET 8.0.1 and later.)

The setting is inherited so can be added to a generic base class.

Update

To do it globally for all objects, subclass the DefaultContractResolver and add the ItemRequired flag to all object contracts:

public class RequireObjectPropertiesContractResolver : DefaultContractResolver
{
    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var contract = base.CreateObjectContract(objectType);
        contract.ItemRequired = Required.Always;
        return contract;
    }
}

And then later, in settings:

var settings = new JsonSerializerSettings { ContractResolver = new RequireObjectPropertiesContractResolver() };

Notes:

Leave a Comment