Reputation: 1641
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.
Upvotes: 2
Views: 179
Reputation: 8962
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.
Upvotes: 3