我有这样一条路线:
@PostMapping("/")
public void sendNotification(@RequestBody PostBody postBody){...}PostBody类中的字段为:
public class PostBody {
    private String type;
    private String payload;
    private String recipients;
    private String callerId;我想知道,我是否可以将这些字段中的一个或多个设为可选,但不是全部?
我猜如果我使用(require = false),所有的字段都是可选的,对吗?
那么有没有办法这样做呢?
谢谢!
发布于 2020-07-16 04:36:49
为此,您可以使用标准的验证注释。只需使用@NotNull或@NotEmpty注释必填字段,并将@Valid添加到请求正文参数中:
@PostMapping("/")
public void sendNotification(@Valid @RequestBody PostBody postBody){...}
public class PostBody {
    @NotEmpty private String type; // String must be non-null and contain at least one character
    @NotNull private String payload; // fails on null but not on ""
    private String recipients; // allows null or "" or any value
    private String callerId;
}发布于 2020-07-16 04:16:11
我的方法是在方法的签名中请求一个映射对象,即@RequestBody Map<String, String> json,然后自己验证这个对象。
String type = json.getOrDefault("type", null);
if (type==null)
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);如果你想使用它,记得改变方法的返回类型。
https://stackoverflow.com/questions/62922771
复制相似问题