【问题标题】:Validate 2 Json Fields for Not Null at the same time同时验证 2 个 Json 字段是否为 Not Null
【发布时间】:2021-09-29 04:34:30
【问题描述】:

我有以下 JSON 。在任何时间点,只有“汽车”或“自行车”字段之一可以为空。不能同时为两者。如何使用杰克逊注释验证 json。 JSON中的所有字段都是必填的

{
    "name": "John",
    "age": 30,
    "car": "Toyota",
    "bike": "Honda"
}

我的 Java Pojo 对象

  public class Example
 {
    @JsonProperty("name")
    public String name;

    @JsonProperty("age")
    public Integer age;

    @JsonProperty("car")
    public String car;

    @JsonProperty("bike")
    public String bike;

【问题讨论】:

标签: json spring spring-boot jackson


【解决方案1】:

根据您的需要,您可以使用 javax.validation.constraints.NotBlank 中的 @NotBlank

 public class Example
 {
    @NotBlank(message = "This field cannot be blank")
    @JsonProperty("name")
    public String name;

    @JsonProperty("age")
    public Integer age;

    @JsonProperty("car")
    public String car;

    @JsonProperty("bike")
    public String bike;
}

您也可以从同一个包中尝试@NotNull 或@NotEmpty。它们有一些差异,看看哪种最适合您的情况。

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 2013-10-16
    • 2015-10-22
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多