首页 > 解决方案 > 同时验证 2 个 Json 字段是否为 Not Null

问题描述

我有以下 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;

标签: jsonspringspring-bootjackson

解决方案


根据您的需要,您可以使用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。他们有一些差异,看看最适合你的情况。


推荐阅读