java - Jackson ObjectMapper.findAndRegisterModules() 无法序列化 LocalDateTime
问题描述
我正在使用 Java Spring-boot RestController。我有一个示例 GET API,我在其中将 LocalDateTime.now() 发送到响应正文中。我已经自定义了 Jackson ObjectMapper 来注册 jackson-datatype-jsr310 模块,但是它无法序列化 LocalDateTime 实例。我尝试了许多在线可用的不同解决方案,但似乎没有任何效果。下面提到了我在此处发布之前的解决方案。
GET API 给出以下错误:
java.time.LocalDateTime
“默认不支持Java 8日期/时间类型:添加模块“com.fasterxml.jackson.datatype:jackson-datatype-jsr310”以启用处理(通过引用链:org.springframework.http.ResponseEntity[“body”]) "
代码:
对象映射器配置:
@Configuration
public class JacksonConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper2(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.build();
objectMapper.findAndRegisterModules();
return objectMapper;
}
}
注意:我尝试过使用 objectMapper.registerModule(new JSR310Module()) 和 objectMapper.registerModule(new JavaTimeModule())。他们也不工作。
休息控制器:
@RestController
public class TestController {
@GetMapping("/test")
public ResponseEntity<Object> test() {
return ResponseEntity.ok().body(LocalDateTime.now());
}
}
我正在使用 spring-boot-starter-parent 2.5.4,因此它会自动将版本 2.12.4 用于所有 jackson.* 依赖项,包括 jackson-datatype-jsr310。
解决方案
欢迎来到 Stack Overflow,就像在您当前使用datetime
的行中记录的那样,ObjectMapper objectMapper = builder.build();objectMapper.findAndRegisterModules();
仅对 2.9 之前的 jackson 2.x 有效,而您的项目包含 jackson 2.12.4 库:就像我在您必须使用以下代码之前链接的官方文档一样:
// Jackson 2.10 and later
ObjectMapper mapper = JsonMapper.builder()
.findAndAddModules()
.build();
或者,如果您更愿意选择性地注册 JavaTimeModule 模块,则可以作为替代方案:
// Jackson 2.10 and later:
ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
更新:我将问题中提出的原始代码修改为以下内容:
@Configuration
public class JacksonConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper2(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
return mapper;
}
}
javatime 模块工作正常并返回正确的LocalTime
json 表示;如果没有配置类,则返回值是正确的 iso 字符串。
推荐阅读
- google-sheets-formula - 用于计算两组时间戳之间持续时间的 GoogleSheet 公式
- javascript - styled-components 内容条件不起作用
- object - 最佳生态系统模拟类层次结构?
- xamarin - 在 Xamarin 中使用 NTLM 授权的 HTTPS 请求问题
- javascript - 收到不支持的 Firbase 云消息传递错误时的错误处理
- google-sheets - 如何在谷歌表格中只显示最近提交的日期?
- c# - C# POST 连接和断开 3g 调制解调器
- java - 如何接收共享方法java的实例化类数组
- xml-parsing - Siebel 输入/输出解析
- next.js - 在 NextJS 中停止缓存重定向