我的 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();
}
}
我猜你正在使用 Jackson 进行 json 序列化,Jackson 现在有一个用于 Java 8 新日期时间 API 的模块,https://github.com/FasterXML/jackson-datatype-jsr310 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>
这是它的用法:
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;
}
}
输出是:
{"time":"2015-07-25T23:09:01.795+0700"}
注意:如果您的 Jackson 版本是 2.4.x,请使用
objectMapper.registerModule(new JSR310Module());
希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)