What is the correct way to use advance property validation when deserializing JSON to Model? I am providing the MyClass
as an example. I need to validate Name( required
) and Email( e-mail address validation
). I do find only [JsonProperty(Required = Required.Always)]
to validate the required properties and nothing for e-mail validation. Unfortunately, Data Annotation validators can't be used from MVC for validation.
One idea which comes to my mind is to create custom ContractResolver
and attach to deserializer where I could perform custom validation. Any other methods to consider?
public class MyClass
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
public string Email { get; set; }
}
_dto = JsonConvert.DeserializeObject<MyClass>(content);
public class MyClass
{
[JsonProperty("name", Required = Required.Always)]
public string Name { get; set; }
[JsonProperty("email", Required = Required.Always)]
public string Email { get; set; }
}
To validate the email you'll have to apply your own regex check after you deserialize.
So I've had some time to test this, and as I suspected, MailAddress
is deserialized to a much more complex json object than a simple address - which means that if you want to keep your json as is, you can't change the property type to MailAddress
.
However, this doesn't mean you can't take advantage of the built in format validation it has in it's constructor, just not with auto-implemented properties.
If you change your class to this -
public class MyClass
{
private string email;
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
[JsonProperty(Required = Required.Always)]
public string Email {
get
{
return email;
}
set
{
var address = new MailAddress(value);
email = value;
}
}
}
Whenever you try to deserialize a json that contains an invalid format email address (and in fact, whenever you try to set this property to a string that's not a valid email address), you'll get a FormatException
:
System.FormatException: The specified string is not in the form required for an e-mail address.
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.