Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json integer being read as java Boolean true

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?

like image 708
rado Avatar asked Oct 27 '25 07:10

rado


1 Answers

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.

like image 78
noiaverbale Avatar answered Oct 28 '25 21:10

noiaverbale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!