When deserializing a JSON string with missing properties, those properties in my class are populated with their default values. I want to change the JsonSerializerSettings
so that, if a property is missing in the JSON and not nullable in the class, an exception is thrown. Conversely, when a property is nullable, it's not required.
I know it's possible with attributes but I want a generic setting.
JsonSerializerSettings settings = new JsonSerializerSettings();
MyParameters parms = JsonConvert.DeserializeObject<MyParameters>(json, settings);
Example:
public class MyParameters
{
public string Message1 { get; set; }
public string Message2 { get; set; }
public int MyInt { get; set; }
public int? MyNullableInt { get; set; }
}
The following JSON should be deserializable:
{
"Message1": "A message",
"MyInt ": 1
}
As result:
Message1 = "A message"
Message2 = null
MyInt = 1
MyNullableInt = null
But the following JSON should cause an exception because MyInt
is missing:
{
"Message1": "A message",
"MyNullableInt": 1
}