In Spring, can I make a single field in @RequestBody optional?

Viewed 8615

I have a route like:

@PostMapping("/")
public void sendNotification(@RequestBody PostBody postBody){...}

And the fields in PostBody class are:

public class PostBody {
    private String type;
    private String payload;
    private String recipients;
    private String callerId;

I am wondering, can I make one or more of these fields optional, but not all of them?

I guess if I use (require = false), all fields will be optional, is that right?

Then is there anyway to do that?

Thanks!

2 Answers

You can use standard Validation annotations for this. Just annotate the mandatory fields with @NotNull or @NotEmpty, and add @Valid to your request body parameter:

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

My approach would be to request for a Map object in method's signature, i.e. @RequestBody Map<String, String> json and then to validate this object on my own, i.e.

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

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

If you want to use it, remember to change the method's return type.

Related