为消费 REST API 映射日期的最佳选择
Best option to map dates for consume REST API
我需要使用 Java/Spring (RestTemplate) 使用 Rest API。
在用 Postman 做了一些冒烟测试后,我看到日期字段有这个结构
"clipStartDate": {
"__type": "Date",
"iso": "2010-09-14T00:00:00.000Z"
}
我尝试使用 java.time.LocalDateTime 在我的 DTO 中映射这些字段。
但是我得到了一个序列化异常。 (org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误: 无法构造 java.time.LocalDateTime
的实例)
这种情况下的最佳做法是什么?
您应该使用 java.time.Instant
,它会正确映射。您问题中的格式是 java.time.Instant
,因此将字段定义为 Instant
,它应该可以工作。
在 属性 之上添加 @JsonDeserialize(using=InstantDeserializer.class)
,如下所示:
@JsonDeserialize(using=InstantDeserializer.class)
private final Instant instant;
您看到的这个错误意味着您的 ObjectMapper
配置不正确。在 Spring Boot 中,这是开箱即用的自动配置,因此如果您使用例如 Spring Boot 2.2,此错误将消失。
然而,如果由于某种原因您没有这种可能性,那么您需要配置一个 ObjectMapper
和一个名为 JavaTimeModule
.
的附加模块
@Bean
public ObjectMapper objectMapper(){
return new ObjectMapper()
.registerModule(new JavaTimeModule());
}
这里有一个补充 article 描述如何进一步自定义 ObjectMapper
我需要使用 Java/Spring (RestTemplate) 使用 Rest API。 在用 Postman 做了一些冒烟测试后,我看到日期字段有这个结构
"clipStartDate": {
"__type": "Date",
"iso": "2010-09-14T00:00:00.000Z"
}
我尝试使用 java.time.LocalDateTime 在我的 DTO 中映射这些字段。
但是我得到了一个序列化异常。 (org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误: 无法构造 java.time.LocalDateTime
的实例)
这种情况下的最佳做法是什么?
您应该使用 java.time.Instant
,它会正确映射。您问题中的格式是 java.time.Instant
,因此将字段定义为 Instant
,它应该可以工作。
在 属性 之上添加 @JsonDeserialize(using=InstantDeserializer.class)
,如下所示:
@JsonDeserialize(using=InstantDeserializer.class)
private final Instant instant;
您看到的这个错误意味着您的 ObjectMapper
配置不正确。在 Spring Boot 中,这是开箱即用的自动配置,因此如果您使用例如 Spring Boot 2.2,此错误将消失。
然而,如果由于某种原因您没有这种可能性,那么您需要配置一个 ObjectMapper
和一个名为 JavaTimeModule
.
@Bean
public ObjectMapper objectMapper(){
return new ObjectMapper()
.registerModule(new JavaTimeModule());
}
这里有一个补充 article 描述如何进一步自定义 ObjectMapper