场景如下。我有一个 ObjectMapper (Jackson 2),它注册了一个 JodaModule,能够序列化和反序列化 Joda DateTime 类型。此 ObjectMapper 使用自定义 JSON 字符串进行测试,并按预期工作。
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。
@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;
}
}
现在,当我联系 web 服务时,它无法反序列化 DateTime 对象,并显示以下错误消息:
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。有人知道我在这里缺少什么吗?