目录
问题描述
解决方法
问题描述
jackson处理LocalDateTime序列化的时候报错
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(LocalDateTime.now());
报错信息
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Java 8 date/time type `java.time.OffsetDateTime` not supported by default:
add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
如果处理Date对象是不会报错的
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(new Date());
// 1684480558531
解决方法
按照异常信息提示,引入模块com.fasterxml.jackson.datatype:jackson-datatype-jsr310
引入依赖
<!-- json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.4</version>
</dependency>
注册JavaTimeModule
ObjectMapper mapper = new ObjectMapper();
// 已过时
// mapper.registerModule(new JSR310Module());
// Jackson 2.7 之后使用JavaTimeModule
mapper.registerModule(new JavaTimeModule());
// 默认输出
mapper.writeValueAsString(LocalDateTime.now())
[2023,5,19,15,21,57,337000000]
发现输出的格式不太对,进一步优化
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
// 设置序列化格式
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(javaTimeModule);
try {
System.out.println(mapper.writeValueAsString(LocalDateTime.now()));
// "2023-05-19 15:29:01"
} catch (JsonProcessingException e) {
e.printStackTrace();
}
完整测试代码
package com.example.demo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class JsonTest {
@Test
public void testJavaTimeModule() {
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
// 设置序列化格式
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(javaTimeModule);
try {
System.out.println(mapper.writeValueAsString(LocalDateTime.now()));
// "2023-05-19 15:29:01"
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
参考
使用Jackson JSR310模块反序列化LocalDateTime
————————————————
版权声明:本文为CSDN博主「彭世瑜」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。