在Java8之前,我们使用ObjectMapper设置DateFormat如下
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
ObjectMapper mapper = <SomeInstantiation>
mapper.setDateFormat(df);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
现在我们有了
java.time.format.DateTimeFormatter
,它是线程安全并且比SimpleDateFormat
更健壮。我想在 ObjectMapper
上替换上述设置。
如何设置
DateTimeFormatter
和 ObjectMapper
?
您可以尝试以下方法:
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTimeDeserializer dateTimeDeserializer = new LocalDateTimeDeserializer(formatter);
LocalDateTimeSerializer dateTimeSerializer = new LocalDateTimeSerializer(formatter);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, dateTimeDeserializer);
javaTimeModule.addSerializer(LocalDateTime.class, dateTimeSerializer);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(javaTimeModule);
jackson-datatype-jsr310
依赖项:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.2</version>
</dependency>