Unable to validate nested object in a json using Spring annotation

99 Views Asked by At

I've a spring boot project which contains a controller that receives a json payload. The json payload looks like this:

{
  "name":"Andrew",
  "age":28,
  "location":{
   "country":"US",
   "city":"New York"

  }
}

and corresponding pojo class

public class Person {
  private String name;
  private int age;
  private Location location;

  // Getters and Setters
}

public class Location {
  private String country;
  private String city;

  @JsonCreator
  public Location (@NotNull String country,@NotNull String city){
    this.country = country;  
    this.city = city;
  }

  // Getters and Setters
}

My requirement is if the location is present in the above json payload, then the country and city should be validated for a null check. If the location is not passed in the payload, then neither country , nor city should be validated. Is there a way to do this validation using Spring annotation? The current annotation @NotNull isn't seem to be working.

1

There are 1 best solutions below

0
On

Put @Valid or @Validated on both classes Persion and Location to active validation.

Also dont forget add @Valid to dto in controller. Refer to this doc