Search code examples
javajsonspring-bootpostjson-schema-validator

JSON schema validation while executing POST request and reading POST data entered by user using spring boot rest api


How to validate (using a specified schema) a JSON input by the user during a POST request using a specified schema (we have to validate the JSON data each time it is received through the POST request)? Also, how to actually extract data entered by the user from a post request? I did the following to extract data entered by the user:

@PostMapping("/all-configs")
public Animal createConfig( @RequestBody Animal ani) {
try {
    System.out.println(ani);//output: net.company.sprinboot.model.Animal@110e19d9
    System.out.println(ani.toString());//output: net.company.sprinboot.model.Animal@110e19d9
    String str = ani.toString();
    System.out.println(str);//output: net.company.sprinboot.model.Animal@110e19d9
}

How can I actually read the JSON data entered by the user in the post request?


Solution

  • How to validate a JSON input by user during a POST request using a specified schema (we have to validate the JSON data each time it is received through the POST request)?

    Add the annotation @Valid(from javax.validation.valid), like so:

    public Animal createConfig(@Valid @RequestBody Animal ani) {
    

    On your Animal DTO, add annotations on the field(s) that you want to be validated, example:

    public class Animal implements Serializable {
        ...
    
        @Size(max = 10)
        @NotBlank
        private String name;
    
        ... 
    }
    

    When Spring Boot finds an argument annotated with @Valid, it bootstraps Hibernate Validator(JSR 380 implementation) and ask it to perform bean validation.

    When the validation fails, Spring Boot throws a MethodArgumentNotValidException.

    Also, how to actually extract data entered by the user form a post request?

    Use the getter method on your Animal POJO. Example:

    String name = ani.getName();
    



    UPDATE:

    Also, if I have a json like: {"hype": {"key1":"value1"} }… then how can I access value1 in hype.key1?

    @RestController
    public class Main {
        @PostMapping("/all-configs")
        public void createConfig(@Valid @RequestBody Animal ani) {
            Map<String, String> hype = ani.getHype();
            System.out.println(hype.get("key1"));
        }
    }
    
    public class Animal implements Serializable {
        private Map<String, String> hype;
    
        public Map<String, String> getHype() {
            return hype;
        }
    
        public void setHype(Map<String, String> hype) {
            this.hype = hype;
        }
    }
    

    Output:

    value1