简体   繁体   中英

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();

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM