2

In the code below, I want both DeserializeObject calls to throw an exception.

public class MyObj
{
    public int MyInt { get; set; }
}

static void Main(string[] args)
{
    var jsonString = "{ }";

    var obj = JsonConvert.DeserializeObject<MyObj>(jsonString); // Doesn't throw

    jsonString = "{ \"MyInt\": null }";

    obj = JsonConvert.DeserializeObject<MyObj>(jsonString); // Does throw
}

I would have expected there be a setting which does the reverse of JsonSerializerSettings.MissingMemberHandling, but I've not been able to find it.

For context, I'm using Json.NET as the request deserializer for an Azure Function API.

Lee
  • 1,591
  • 1
  • 14
  • 28

1 Answers1

3

You may use JsonProperty attribute with Required = Required.Always :

public class MyObj
{
    [JsonProperty(Required = Required.Always)]
    public int MyInt { get; set; }
}

From Required enum doc:

Always ... The property must be defined in JSON and cannot be a null value.

Renat
  • 7,718
  • 2
  • 20
  • 34