将DateTimeFormatter与ObjectMapper一起使用

时间:2016-10-10 09:22:22

标签: java objectmapper

在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上替换上面的设置。

如何使用ObjectMapper

设置DateTimeFormatter

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

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>