gabriel119435
gabriel119435

Reputation: 6832

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?

Upvotes: 4

Views: 2815

Answers (1)

noiaverbale
noiaverbale

Reputation: 1688

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.

Upvotes: 5

Related Questions