0

I have below JSON . At any point of time only one of the field "car" or "bike" can be null .Not both at the same time.How can I validate json using Jackson annotations. All the fields in JSON are mandatory

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

My Java Pojo Objects

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

    @JsonProperty("age")
    public Integer age;

    @JsonProperty("car")
    public String car;

    @JsonProperty("bike")
    public String bike;
Pale Blue Dot
  • 511
  • 2
  • 13
  • 33
  • 1
    Take a look at [@Valid when creating objects with jackson without controller](https://stackoverflow.com/q/55457754/51591). You can implement a new validator which would check these two fields: [How can I validate two or more fields in combination?](https://stackoverflow.com/questions/2781771/how-can-i-validate-two-or-more-fields-in-combination) – Michał Ziober Jul 22 '21 at 09:46

1 Answers1

0

Depending what you want, you can use @NotBlank from javax.validation.constraints.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;
}

You can also try @NotNull or @NotEmpty from same package. They have some differences, see what best fit on your case.

Rhames Lima
  • 28
  • 1
  • 5