小编典典

Jackson在Spring Boot中错误地序列化了ZonedDateTime

spring-boot

我有一个使用Spring Boot和Jetty的简单应用程序。我有一个简单的控制器返回一个具有Java 8的对象ZonedDateTime

public class Device {
  // ...
  private ZonedDateTime lastUpdated;

  public Device(String id, ZonedDateTime lastUpdated, int course, double latitude, double longitude) {
    // ...
    this.lastUpdated = lastUpdated;
    // ...
  }

  public ZonedDateTime getLastUpdated() {
    return lastUpdated;
  }
}

在我这里,RestController我简单地拥有:

@RequestMapping("/devices/")
public @ResponseBody List<Device> index() {
  List<Device> devices = new ArrayList<>();
  devices.add(new Device("321421521", ZonedDateTime.now(), 0, 39.89011333, 24.438176666));

  return devices;
}

我期望ZonedDateTime可以根据ISO格式进行格式化,但是相反,我得到了整个此类的JSON转储:

"lastUpdated":{"offset":{"totalSeconds":7200,"id":"+02:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"zone":{"id":"Europe/Berlin","rules":{"fixedOffset":false,"transitionRules":[{"month":"MARCH","timeDefinition":"UTC","standardOffset":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"offsetBefore":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"offsetAfter":{"totalSeconds":7200,"id":"+02:00", ...

我只有一个spring-boot-starter-web应用程序,使用spring-boot-starter-jetty和排除spring- boot-starter-tomcat

为什么Jackson在Spring Boot中的行为如此?

更新

对于那些正在寻找逐步解决方案的完整指南的人,我在问了以下问题后便发现了这一点:http :
//lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-
json/


阅读 318

收藏
2020-05-30

共1个答案

小编典典

有一个库jackson-datatype-jsr310。尝试一下。

该库涵盖了新的datetime API,并且还包含序列化器ZonedDateTime

您只需要添加JavaTimeModule

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

更新

要将日期时间转换为ISO-8601字符串,应禁用WRITE_DATES_AS_TIMESTAMPS功能。您可以通过覆盖ObjectMapperbean或使用应用程序属性来轻松实现:

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false
2020-05-30