0

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();
shalama
  • 1,133
  • 1
  • 11
  • 25
  • 1
    Can you annotate the relevant field in `MyObject` in any way. Can't be sure without looking it up. – jr593 Dec 10 '19 at 08:35
  • Possible duplicate of [How do I deserialize to Boolean.class from Json object in case insensitive manner using Jackson?](https://stackoverflow.com/questions/58999975/how-do-i-deserialize-to-boolean-class-from-json-object-in-case-insensitive-manne). – LHCHIN Dec 10 '19 at 08:47

1 Answers1

2

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());
    }
}
Petr Aleksandrov
  • 1,434
  • 9
  • 24