简体   繁体   中英

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM