'Optional fields in Java DTO with validation constraint
I've created a DTO with some properties with validation constraint (like all the properties must be present in JSON Object). Now, I want to make that DTO in a way like if a particular property is missing in JSON Object, it causes no error.
public class UserDTO{
private String name;
private String address;
private String email;
private String mobileNumber;
}
Now the JSON Object which I want to work could be like this (with missing email).
{
name:"Hamza",
address:"ABC",
mobileNumber:"12345"
}
What should be done? Is there any annotation which makes the field optional?
Solution 1:[1]
you can add @JsonIgnoreProperties(ignoreUnknown = true) to ignore all unknow fields (if you don't know which need to ignore). or you can add @JsonIgnore on top of the field (if you know which field need to ignore during deserialization).
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDTO {
private String name;
private String address;
private String email;
private String mobileNumber;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mazhar Ibna Zahur |