Spring RestTemplate与Jackson作为HttpMessageConverter和joda DateTime属性无法反序列化 [英] Spring RestTemplate with Jackson as HttpMessageConverter and joda DateTime property fails to deserialize
问题描述
方案如下。我有一个ObjectMapper(Jackson 2),它注册了一个JodaModule,能够序列化和反序列化Joda DateTime类型。这个ObjectMapper使用自定义JSON字符串进行测试,并按预期工作。
The scenario is as follows. I have an ObjectMapper (Jackson 2) that registers a JodaModule, capable of serializing and de-serializing Joda DateTime type. This ObjectMapper is tested with custom JSON strings and works as expected.
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
objectMapper.setDateFormat(new ISO8601DateFormat());
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
我有一个RestTemplateFactory,它负责实例化RestTemplate,并将之前配置的ObjectMapper bean设置为RestTemplate。
I have an RestTemplateFactory which is responsible for instantiating a RestTemplate, and it sets the previously configured ObjectMapper bean to the RestTemplate.
@Configuration
public class RestTemplateFactory {
@Autowired
private ObjectMapper objectMapper;
@Bean
public RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
// restTemplate.setMessageConverters(messageConverters); // This line was missing, but needs to be here. See answer.
return restTemplate;
}
}
现在,当我联系网络服务时,它无法取消使用以下错误消息序列化DateTime对象:
Now when I contact the webservice it fails to de-serialize the DateTime object with the following error message:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not instantiate value of type [simple type, class org.joda.time.DateTime] from String value; no single-String constructor/factory method
此外,从不调用DateTimeDeserializer.class。任何人都知道我在这里缺少什么?
Also the DateTimeDeserializer.class is never called. Anyone has an idea what I am missing here?
推荐答案
好的,我在createRestTemplate()方法中缺少这一行。
OK, I was missing this line in my createRestTemplate() method.
restTemplate.setMessageConverters(messageConverters);
这篇关于Spring RestTemplate与Jackson作为HttpMessageConverter和joda DateTime属性无法反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!