在春季,我可以将@RequestBody中的单个字段设为可选吗?

时间:2020-07-15 19:51:52

标签: java spring spring-boot

我的路线类似:

@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),所有字段都是可选的,对吗?

那有什么可以做的?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以为此使用标准的验证批注。只需使用@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;
}

答案 1 :(得分:0)

我的方法是请求方法签名中的Map对象,即@RequestBody Map<String, String> json,然后自己验证该对象,即

String type = json.getOrDefault("type", null);

if (type==null)
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

如果要使用它,请记住更改该方法的返回类型。

答案 2 :(得分:0)

如果通过说“可选”来表示可为空,则默认情况下它们为可为空。如果您确实想要Optional,则需要在Optional类中将这些字段定义为PostBody