If I have a DTO class containing value type properties, how can I idiomatically use Newtonsoft to deserialize JSON to my DTO class while ensuring that the JSON defines the value type, possibly containing the default
value for the type? So far the methods I have seen rely on checking if the value is the default
value, however, this is not a suitable solution when the default
value is also a valid value for the property.
Example
public class MyDto
{
public bool MyProp { get; set; }
}
JSON | Can deserialize to MyDto |
---|---|
{"MyProp": true} |
true |
{"MyProp": false} |
true |
{} |
false |
Current solution
Currently I use System.ComponentModel.DataAnnotations.RequiredAttribute
and declare the type as nullable, but this only works during model binding (instead of any deserialization), and leads to excessive use of !
when referencing the property.
public class MyDto
{
[Required]
public bool? MyProp { get; set; }
}