-1

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.

2
  • What specifically do you mean by "not working"? Please take the tour, visit the help center and read How to Ask to learn how to use this site effectively. Commented Oct 19, 2023 at 0:20
  • What will you do with NullPointerException if this happens? Commented Oct 19, 2023 at 5:22

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.