Java 8 日期时间类型使用 Spring Boot 序列化为对象

Syd*_*ney 21 spring spring-boot

我有一个包含 Java 8 日期时间类型字段的实体。问题是这些字段被序列化为对象。我添加了jackson-datatype-jsr310依赖项,因此 Spring Boot 1.5.7 会自动配置JavaTimeModule处理 Java 8 日期时间类型。看来该模块没有注册(我在 JavaTimeModule 构造函数中放置了一个断点)。我知道我不需要定制ObjectMapper。我花了几个小时阅读该问题,解决方案始终是添加jackson-datatype-jsr310依赖项,但它在我的情况下不起作用。

实体:

@Entity
public class DateTimeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private LocalDate localDate;

    private LocalDateTime localDateTime;

    private Instant instant;

    private OffsetDateTime offsetDateTime;

    private ZonedDateTime zonedDateTime;

}
Run Code Online (Sandbox Code Playgroud)

RestController 方法:

@GetMapping("/datetimes/{id}")
public ResponseEntity<DateTimeEntity> getById(@PathVariable Long id) {
    DateTimeEntity dateTimeEntity = dateTimeRepository.findOne(id);
    return new ResponseEntity<DateTimeEntity>(dateTimeEntity, HttpStatus.OK);

}
Run Code Online (Sandbox Code Playgroud)

返回的 JSON 对象:

    {
    "id": 1,
    "localDate": null,
    "localDateTime": null,
    "instant": {
        "epochSecond": 1508772600,
        "nano": 0
    },
    "offsetDateTime": {
        "offset": {
            "totalSeconds": 0,
            "id": "Z",
            "rules": {
                "fixedOffset": true,
                "transitionRules": [],
                "transitions": []
            }
        },
        "dayOfMonth": 23,
        "dayOfWeek": "MONDAY",
        "dayOfYear": 296,
        "month": "OCTOBER",
        "monthValue": 10,
        "year": 2017,
        "hour": 15,
        "minute": 30,
        "nano": 0,
        "second": 0
    },
    "zonedDateTime": {
        "offset": {
            "totalSeconds": 0,
            "id": "Z",
            "rules": {
                "fixedOffset": true,
                "transitionRules": [],
                "transitions": []
            }
        },
        "zone": {
            "totalSeconds": 0,
            "id": "Z",
            "rules": {
                "fixedOffset": true,
                "transitionRules": [],
                "transitions": []
            }
        },
        "dayOfMonth": 23,
        "dayOfWeek": "MONDAY",
        "dayOfYear": 296,
        "month": "OCTOBER",
        "monthValue": 10,
        "year": 2017,
        "hour": 15,
        "minute": 30,
        "nano": 0,
        "second": 0,
        "chronology": {
            "id": "ISO",
            "calendarType": "iso8601"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

POM 文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>framework-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <mockito.version>2.11.0</mockito.version>
        <org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>${jackson.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.5</version>
                <executions>
                    <execution>
                        <id>output-html</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <backend>html</backend>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
Run Code Online (Sandbox Code Playgroud)

The*_*eff 38

我在Spring Boot从2.3.7升级到2.5.1时开始遇到这个问题。

如果您定义了 ObjectMapper @Bean,那么您将需要向其注册时间模块。

@Bean
public ObjectMapper defaultMapper() {
    ObjectMapper objectMapper = new ObjectMapper(); 
    objectMapper.registerModule(new JavaTimeModule()); 
    return objectMapper;
}
Run Code Online (Sandbox Code Playgroud)

很多时候,编码人员在使用 Jackson 序列化时只会创建一个“new ObjectMapper()”,因此请注意使用普通映射器,而不是自动装配注册了时间模块的预配置默认值。

如前所述,您需要 jackson-datatype-jsr310,但这作为托管版本包含在 Spring Boot 中。

如果您没有手动定义对象映射器 bean,那么 spring boot 应该自动提供一个注册了时间模块的对象映射器 bean。

  • 我通过在 localdatetime 字段之前添加 @JsonSerialize(using = LocalDateTimeSerializer.class) 解决了这个问题。我认为这是最新版本的jsr310中的一个错误 (2认同)

zaq*_*otr 8

您也可以尝试使用

ObjectMapper objectMapper = JsonMapper.builder()
        .addModule(new JavaTimeModule())
        .build();
Run Code Online (Sandbox Code Playgroud)

JavaTimeModule 来自包 com.fasterxml.jackson.datatype.jsr310 我使用了库 jackson-datatype-jsr310-2.13.3.jar


Bap*_*ais 7

根据如何自定义 ObjectMapper

com.fasterxml.jackson.databind.Module 类型的任何 bean 都将自动注册到自动配置的 Jackson2ObjectMapperBuilder 并应用于它创建的任何 ObjectMapper 实例。当您向应用程序添加新功能时,这提供了一种贡献自定义模块的全局机制。

仅仅添加依赖项是不够的,您必须声明一个@Bean模块,如下所示:

@Bean
public Module dateTimeModule(){
    return new JavaTimeModule();
}
Run Code Online (Sandbox Code Playgroud)

Plusjackson-datatype-jsr310模块已弃用,您应该使用JavaTimeModule代替。


Syd*_*ney 4

解决方案是将依赖项添加到类路径中。由于某种原因,它不在 IDE 中。

尽管依赖项已被弃用,但spring-boot-autoconfigure模块仍然使用它。请参阅Spring Boot 代码

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

当它位于类路径中时,Java 8 日期和时间对象将被序列化为时间戳。