具有验证约束的Java DTO中的可选字段

发布于 2025-01-24 01:23:26 字数 402 浏览 3 评论 0原文

我已经创建了一个具有验证约束的属性的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谎言 2025-01-31 01:23:26

您可以添加@jsonignoreproperties(ignoreunknown = true)来忽略所有不知道的字段(如果您不知道需要忽略哪个字段)。或者,您可以在字段之上添加@jsonignore(如果您知道在避难过程中需要忽略哪个字段)。

@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDTO {
    private String name;
    private String address;
    private String email;
    private String mobileNumber;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文