@Valid 注释不适用于 json 请求列表

@Valid annotation is not working for list of json request

我试图验证 json 请求的列表,但它不起作用。

Json请求

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

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

这是我的控制器class

控制器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);
        }

此处@Valid 注解不验证列表

POJOclass

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;
}
        
    }

请帮我解决这个问题。

  1. Spring-boot2.3.0后需要手动添加 spring-boot-starter-validation 到您的项目。

  2. 使用@RequestBody List<@Valid Req> reqs代替@RequestBody @Valid List<Req> reqs

  3. 在控制器Class上添加@Validated

  4. 它会抛出ConstraintViolationException,所以你可能想把它映射到400 Bad Request.

来源:Baeldung,