Search code examples
javajsonresttemplatespring-rest

Spring RestTemplate boolean caps deserialization


I'm using spring RestTemplate to deserialise a json to object. Challenge I'm having is that the boolean values in the json are all in caps. When I try to deserialise them i get a HttpMessageNotReadableException.

spring.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.lang.Boolean from String "FALSE": only "true" or "false" recognized;

So my question is how to add a custom mapping for this boolean value.

ResponseEntity<List<MyObject>> responseEntity = restTemplate.exchange(url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<MyObject>>() {
                });
        return responseEntity.getBody();

Solution

  • You can use Custom Deserializer. Take a look at com.fasterxml.jackson.databind.JsonDeserializer annotation.

    See MyBooleanDeserializer example bellow. It can handle values in CAPS:

    public class MyObject {
        @JsonDeserialize(
                using = MyBooleanDeserializer.class,
                as = Boolean.class
        )
        private boolean bool;
    }
    
    class MyBooleanDeserializer extends JsonDeserializer {
        @Override
        public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            return Boolean.parseBoolean(jsonParser.getValueAsString().toLowerCase());
        }
    }