简体   繁体   中英

RestTemplate.exchange gives UnrecognizedPropertyException (ignores @JsonIgnoreProperties)

I'm using the @JsonIgnoreProperties to ignore the extra properties that my rest API is returning.

While this works for an ObjectMapper, it does not work from the exchange method on a RestTemplate. I still get the UnrecognizedPropertyException when the server returns a property not found in the POJO.

Is there a way to support this for the exchange method?

Here's my code (I'm using com.fasterxml.jackson.annotation.JsonIgnoreProperties)

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {

    private String id = "";

    public MyObject(String id) {
        this.id = id;
    }
    // .... getter and setter
}

...
ResponseEntity<MyObject> restResponse = 
                restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, request, MyObject.class);

You are probably using org.codehaus.jackson.annotate.JsonIgnoreProperties. You have to use com.fasterxml.jackson.annotation.JsonIgnoreProperties with RestTemplate .

Or you can also configure your restTemplate with MappingJackson2HttpMessageConverter to ignore unknown properties. Something like:

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(mapper);
restTemplate.getMessageConverters().add(converter);

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