【问题标题】:RestTemplate.exchange gives UnrecognizedPropertyException (ignores @JsonIgnoreProperties)RestTemplate.exchange 给出 UnrecognizedPropertyException (忽略 @JsonIgnoreProperties)
【发布时间】:2018-01-24 20:23:45
【问题描述】:

我正在使用 @JsonIgnoreProperties 来忽略我的其余 API 返回的额外属性。

虽然这适用于 ObjectMapper,但它不适用于 RestTemplate 上的交换方法。当服务器返回 POJO 中未找到的属性时,我仍然会收到 UnrecognizedPropertyException。

有没有办法支持这种交换方式?

这是我的代码(我使用的是 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);

【问题讨论】:

  • restTemplate 对象是如何创建的?
  • 就是这样实例化的:RestTemplate restTemplate = new RestTemplate()
  • 你用的是哪个版本的jackson?
  • 我使用的jackson版本是2.4.4

标签: java json spring rest


【解决方案1】:

您可能正在使用org.codehaus.jackson.annotate.JsonIgnoreProperties. 您必须将com.fasterxml.jackson.annotation.JsonIgnorePropertiesRestTemplate 一起使用。

或者您也可以使用MappingJackson2HttpMessageConverter 配置您的restTemplate 以忽略未知属性。类似的东西:

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

【讨论】:

  • 我正在使用 com.fasterxml.jackson.annotation.JsonIgnoreProperties
  • 您也可以尝试使用 MappingJackson2HttpMessageConverter 配置您的 restTemplate。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2020-05-06
  • 2020-09-13
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
相关资源
最近更新 更多