4

Inside a REST API request json body, I'm passing "argument1":true and it works. But I discovered that when using any number it converts it to true. Only when using explicitly false it turns into false. I'm using Spring Boot ResponseEntityExceptionHandler and @RestControllerAdvice to handle all exceptions. How can I cast any exception when converting 534 to true?

2
  • Do you expect argument1 to be of type boolean or int? I mean, you want spring binder to throw exception when argument1 is integer and not boolean? Commented Feb 12, 2019 at 15:18
  • @noiaverbale, exactly as you stated. I want to reject any non boolean values (only true or false) Commented Feb 12, 2019 at 15:21

1 Answer 1

5

Add in your controller a method annotated with @InitBinder and provide a custom boolean editor

@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    webDataBinder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("true", "false", false));
}

Spring registers a default CustomBooleanEditor mapping "true", "on", "yes" and any non zero number as true (also allowing empty value as false) throwing IllegalArgumentException when value is not valid.

You can either override it or provide your own implementation throwing a specific exception.

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

3 Comments

Thanks for your info. Could you please link any documentation towards this information? Thanks in advance
It's not a much, but InitBinder. Can't find a list of default converters/editor right now.
I don't get this working when having a @RequestBody.....so it is no forms just a rest endpoint.....should it work in that scenario also ?

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.