1

Have a restcontroller mapping with a @RequestBody TypeA in it.

TypeA is resolved correctly, even if I send a {} as a body. The thing I'm trying to achieve is to have the same logic for when the body isn't sent at all (the @RequestBody is null).

Code:

@PostMapping('/post')
public ResponseEntity processPost(@RequestBody(required=false) Optional<TypeA> body) {
       return service.someAction(body.orElse(new TypeA());
}

So far, the only possible solution I see is to set the required = false, wrap the type in Optional, and work with the .orElseGet(...new), which works, but doesn't look valid.

Is there a proper way to have this?

6
  • I don't understand what you want, could you add some examples and what exactly you expect ? Commented Aug 6, 2019 at 14:39
  • I am trying to achieve the same behavior for both empty and null RequestBody Commented Aug 6, 2019 at 14:51
  • But your desired behaviour is unclear, some code would help Commented Aug 6, 2019 at 15:00
  • Added a 'how it is at the moment' example Commented Aug 6, 2019 at 15:13
  • Ok thanks, but doesn't look valid. - Personally, I think that the only thing wrong is treating {} and null as the same. But if you really need this, I don't see anything wrong with your code Commented Aug 6, 2019 at 16:42

2 Answers 2

1

You can try this

@PostMapping('/post')
    public ResponseEntity processPost(@NotNull(message = "you can add null description") @RequestBody TypeA body) {

    }

Sign up to request clarification or add additional context in comments.

Comments

0

I would do something like this:

@PostMapping('/post')
public ResponseEntity processPost(@RequestBody(required=false) TypeA body) {
       return service.someAction(body == null ? new TypeA(): body);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.