Spring RestTemplate与Jackson作为HttpMessageConverter和joda DateTime属性无法反序列化

时间:2014-01-25 19:50:45

标签: spring jackson jodatime jackson-modules

方案如下。我有一个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;
  }
}

现在当我联系webservice时,它无法使用以下错误消息反序列化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。任何人都知道我在这里缺少什么?

2 个答案:

答案 0 :(得分:13)

好的,我在createRestTemplate()方法中错过了这一行。

restTemplate.setMessageConverters(messageConverters);

答案 1 :(得分:2)

添加依赖

      <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
        <version>2.9.0.pr4</version>
    </dependency>

并使用DateTimeDeserializer.class进行反序列化,如下所示

@JsonDeserialize(using = DateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy", timezone = "Europe/Berlin")
private DateTime date;

对我来说很好。无需添加自定义消息转换器。