将 DateTimeFormatter 与 ObjectMapper 结合使用

问题描述 投票:0回答:1

在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

java objectmapper
1个回答
10
投票

您可以尝试以下方法:

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>
© www.soinside.com 2019 - 2024. All rights reserved.