Search code examples
javavalidationspring-boot-maven-plugin

@Valid annotation is not working for list of json request


I tried to validate the list of json request but it is not working.

Json request

[
  {
    "name": "AA",
    "location": "Newyork"
  },

  {
    "name": "BB",
    "location": "Delhi"
  }
]

Here is my controller class

Controller class

@RestController
@Validated
@RequestMapping("/v1.0")

public class Controller {
        public ResponseEntity<List<Response>> ConversionResponse(    @RequestBody List<@Valid Request> req) throws Throwable {
       List<Response> response = new ArrayList<Response>();
            for (request request : req) {
    
                response = services.conversion(request, response);
    
            }
        return new ResponseEntity<>(response, HttpStatus.OK);
        }

Here @Valid annotation doesnot validate the list

POJO class

public class Request{  
    
@NotNull
private String name;

@NotNull(message="Location should not be null")
private String location;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getLocation() {
    return location;
}
public void setLocation(String location) {
    this.location = location;
}
        
    }

Please help me on this.


Solution

    1. After Spring-boot 2.3.0, you need to manually add the spring-boot-starter-validation to your project.

    2. Use @RequestBody List<@Valid Req> reqs instead of @RequestBody @Valid List<Req> reqs.

    3. Add @Validated on the Controller Class.

    4. It will throw ConstraintViolationException, so you may want to map it into 400 Bad Request.

    sources: Baeldung, Question 39348234