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.
CodePudding user response:
After Spring-boot 2.3.0, you need to manually add the
spring-boot-starter-validation
to your project.Use
@RequestBody List<@Valid Req> reqs
instead of@RequestBody @Valid List<Req> reqs
.Add
@Validated
on the Controller Class.It will throw
ConstraintViolationException
, so you may want to map it into400 Bad Request
.
sources: Baeldung, Question 39348234