首页 > 解决方案 > 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。

标签: javajsonspring-bootjacksonjsr310

解决方案


欢迎来到 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 模块工作正常并返回正确的LocalTimejson 表示;如果没有配置类,则返回值是正确的 iso 字符串。


推荐阅读