diff --git a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java index c9f30dc6e3..5b50b75675 100644 --- a/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java +++ b/spring-boot-modules/spring-boot-validations/src/main/java/com/baeldung/deserializer/BooleanDeserializer.java @@ -8,11 +8,14 @@ import com.fasterxml.jackson.databind.JsonDeserializer; public class BooleanDeserializer extends JsonDeserializer { @Override - public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String value = p.getText(); - if (value != null && !value.equals("TRUE") && !value.equals("FALSE")) { - throw new IllegalArgumentException("Boolean value must come as Capital TRUE or FALSE"); + public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String value = parser.getText(); + if (value != null && (value.equals("TRUE") || value.equals("1") || value.equals("+"))) { + return Boolean.TRUE; + } else if (value != null && (value.equals("FALSE") || value.equals("0") || value.equals("-"))) { + return Boolean.FALSE; + } else { + throw new IllegalArgumentException("Only values accepted as Boolean are TRUE, FALSE, +, -, 1 , 0"); } - return Boolean.valueOf(value); } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java b/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java index 78950e4c0e..0ff786bd4c 100644 --- a/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java +++ b/spring-boot-modules/spring-boot-validations/src/test/java/com/baeldung/controller/ValidationControllerUnitTest.java @@ -84,7 +84,22 @@ class ValidationControllerUnitTest { .getResponse() .getContentAsString(); - assertEquals("Boolean value must come as Capital TRUE or FALSE", output); + assertEquals("Only values accepted as Boolean are TRUE, FALSE, +, -, 1 , 0", output); + } + + @Test + void testInvalidBooleanFromJson() throws Exception { + + String postBody = "{\"boolField\":true,\"trueField\":true,\"falseField\":false,\"boolStringVar\":\"6\"}"; + + String output = mockMvc.perform(post("/validateBoolean").contentType("application/json") + .content(postBody)) + .andReturn() + .getResponse() + .getContentAsString(); + + assertEquals("Only values accepted as Boolean are TRUE, FALSE, +, -, 1 , 0", output); + } @Test