Spring Data JPA - 用于json序列化的ZonedDateTime格式

Chr*_*tis 15 java spring json jpa spring-data-jpa

我的json序列化有问题ZonedDateTime.当转换为json时,它产生了一个巨大的对象,我不希望每次都传输所有这些数据.所以我尝试将其格式化为ISO,但它不起作用.我怎样才能让它格式化?

这是我的实体类:

@MappedSuperclass
public abstract class AuditBase {

    @Id
    @GeneratedValue
    private Long id;

    @CreatedDate
    private ZonedDateTime createdDate;

    @LastModifiedDate
    private ZonedDateTime lastModifiedDate;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    public ZonedDateTime getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(ZonedDateTime lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    public ZonedDateTime getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(ZonedDateTime createdDate) {
        this.createdDate = createdDate;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @PrePersist
    public void prePersist() {
        this.createdDate = ZonedDateTime.now();
        this.lastModifiedDate = ZonedDateTime.now();
    }

    @PreUpdate
    public void preUpdate() {
        this.lastModifiedDate = ZonedDateTime.now();
    }
}
Run Code Online (Sandbox Code Playgroud)

toa*_*ndv 31

我猜你正在使用Jackson进行json序列化,Jackson现在有一个用于Java 8新日期时间API的模块,https://github.com/FasterXML/jackson-datatype-jsr310.

将此依赖项添加到您的pom.xml中

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

这是它的用法:

 public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    System.out.println(objectMapper.writeValueAsString(new Entity()));
}

static class Entity {
    ZonedDateTime time = ZonedDateTime.now();

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
    public ZonedDateTime getTime() {
        return time;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

{"time":"2015-07-25T23:09:01.795+0700"}
Run Code Online (Sandbox Code Playgroud)

注意:如果您的Jackson版本是2.4.x使用

objectMapper.registerModule(new JSR310Module());
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 我有一些很奇怪的事情:{"time":1473923145.038000000}。有了你的解决方案,我现在可以根据需要 {"time":"2016-09-15T07:57:26.602+0000"} 。 (2认同)