Search code examples
c#json.netdeserialization

Deserialization and throw exception for required property when it is null


I'm probably missing something. I'd like to test behavior when an API call response returns a property of null and I would like to throw an exception when that happens.

I have a Form object as follow

public class Form
{
    [Required]
    public string Html { get; set; }
    public string Json { get; set; }
    public string Name { get; set; }
}

I have initialized an object

var myData = new
{
    Json = "foo",
};

string jsonData = JsonConvert.SerializeObject(myData);
var response = JsonConvert.DeserializeObject<Form>(File.ReadAllText(jsonPath));

I was expecting to have an exception since the Html property is required and not nullable, but actually getting the object as

{
    Html = null, 
    Json = foo,
    Name = null
}

I have tried to use JsonSerializerSettings as follows but this actually throws an exception only when there is an additional unwanted property and not when there's a missing one.

JsonSerializerSettings config = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error, NullValueHandling = NullValueHandling.Include};
var res =  JsonConvert.DeserializeObject<Form>(json,config);

Solution

  • You need [JsonProperty(Required = Required.Always)].

    public class Form
    {
        [JsonProperty(Required = Required.Always)]
        public string Html { get; set; }
        public string Json { get; set; }
        public string Name { get; set; }
    }
    

    Sample Program

    While [Required] attribute is for Data Annotation.


    Reference

    JsonPropertyAttribute required