具有验证约束的Java DTO中的可选字段
我已经创建了一个具有验证约束的属性的DTO(就像所有属性一样,必须在JSON对象中)。现在,我想以JSON对象中缺少特定属性的方式进行DTO,这不会导致错误。
public class UserDTO{
private String name;
private String address;
private String email;
private String mobileNumber;
}
现在,我想使用的JSON对象可能就是这样(缺少电子邮件)。
{
name:"Hamza",
address:"ABC",
mobileNumber:"12345"
}
该怎么办?是否有任何使字段可选的注释?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以添加@jsonignoreproperties(ignoreunknown = true)来忽略所有不知道的字段(如果您不知道需要忽略哪个字段)。或者,您可以在字段之上添加@jsonignore(如果您知道在避难过程中需要忽略哪个字段)。
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).