14

场景如下。我有一个 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。有人知道我在这里缺少什么吗?

4

2 回答 2

18

好的,我的 createRestTemplate() 方法中缺少这一行。

restTemplate.setMessageConverters(messageConverters);
于 2014-01-25T20:13:02.347 回答
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;

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

于 2017-06-28T14:53:19.880 回答