我正在使用 the Jackson Datatype JSR310 page 中描述的库但我仍然很难让它工作。
我已经配置了以下 bean:
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
return mapper;
}
当我调用我的 REST API 时,日期格式输出为 yyyy-MM-dd'T'HH:ss.SSSSSS
,例如2015-04-11T00:10:38.905847
。这由我的 AngularJS 代码处理得很好。
当我想向 REST API 提交内容时,日期被发布为 yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
,例如2015-04-09T08:30:00.000Z
Jackson 一直提示最后的“Z”。如果我查看文档中的 LocalDateTimeDeserializer
,它使用的是 DateTimeFormatter.ISO_LOCAL_DATE_TIME
,它归结为 ISO_LOCAL_DATE'T'ISO_LOCAL_TIME
,它提到它没有覆盖区域。
所以我想我应该在我正在创建的 ObjectMapper
上设置 DateFormat
:
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
return mapper;
}
但这没有任何作用。我将其更改为类似 yyyy-MM-dd
的简单格式,但序列化日期仍保持以前的格式,反序列化也不受影响。
为了让它正常工作,我在这里做错了什么?据我所知,我的 JavaScript 代码中的日期格式是 ISO 8601 格式......
最佳答案
不必编写自己的序列化程序。使用默认的就足够了,但是用另一种格式(time_zone
)创建一个实例,这样超出的部分就被剪掉了:
new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME)
在我的例子中,我有一个像这样的 contextResolver
可以在配置级别实现:
@Service
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
JavaTimeModule javaTimeModule=new JavaTimeModule();
// Hack time module to allow 'Z' at the end of string (i.e. javascript json's)
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
mapper.registerModule(javaTimeModule);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
关于java - 使用 Jackson JSR310 模块反序列化 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571587/