28

In Json.NET, how do I make ALL properties required upon deserialization? I know that I can do this with attributes on the messages, but I don't want to do that. Mainly because it would require my message library to take on an external dependency.

I tried the MissingMemberHandling.Error setting, but it does the opposite of what I want. I'm okay with the JSON having extra properties. I want it to fail when any target object properties are missing in the JSON.

I'm actually deserializing to F# records, and the properties can't ordinarily be null anyway. (They can't be assigned null by normal means in code.) But Json.NET happily defaults properties to null under the covers when data is missing.


F# version of accepted answer

Resolver

open System
open Newtonsoft.Json
open Newtonsoft.Json.Serialization

type RequireAllPropertiesContractResolver() =
    inherit DefaultContractResolver()

    override me.CreateObjectContract(objectType:Type) =
        let contract = base.CreateObjectContract(objectType)
        contract.ItemRequired <- new Nullable<Required>(Required.Always)
        contract

In the settings

let settings = new JsonSerializerSettings() // default settings
...
settings.ContractResolver <- new RequireAllPropertiesContractResolver()

2 Answers 2

41

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:

12
  • Adding an attribute to all class and their subclasses is a no-go. At that point, it's easier just to wrap the call that uses the data in a try/catch for null reference exceptions, which is what I am currently forced to do instead of catch it at the source. Commented Apr 15, 2015 at 20:47
  • Maybe I misunderstood your question, I thought you objected to wrapping all properties?
    – dbc
    Commented Apr 15, 2015 at 20:48
  • 1
    This worked perfect for me, do you know if there is a way to get a list of all the missing properties in one error? right now I need to run it, find first error, fix, and then keep going which is tedious
    – TWilly
    Commented Dec 8, 2017 at 16:25
  • 1
    Might be worth noting that this works both ways, meaning that serialization will fail if an object has a null property. I'm struggling to figure out how to have different ContractResolvers for serializing and deserializing in an ASP.NET Core 2 Web API. Commented Mar 11, 2019 at 16:39
  • 1
    @YarekT - maybe you should ask a separate question with a minimal reproducible example then. This was written for f# which never wants null reference values, maybe you need something more general.
    – dbc
    Commented Apr 4, 2022 at 2:29
3

I know I am late on party here, but... Accepted answer forces all properties to be available, which could be not so good for case when your record contains Option types combining with NullValueHandling.Ignore parameter on JsonSerializerSettings. In that case you would require option type to be present, which is too limiting. We found this solution works for us:

type RequireAllPropertiesContractResolver() =
    inherit CamelCasePropertyNamesContractResolver()

    override __.CreateProperty(memb, serialization) =
        let prop = base.CreateProperty(memb, serialization)
        let isRequired = not (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() = typedefof<option<_>>)
        if isRequired then prop.Required <- Required.Always
        prop

I hope it helps someone.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.