使用jackson转换日期/时间时保留时区信息

db2dz4w8  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(414)

我有我的 ObjectMapper 配置如下:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

然后我有一个数据类:

@Data
public class TimeTracker {
  private OffsetDateTime timestamp;
}

以及以下使用rfc3339格式的时间戳的测试:

// Given
String json =
  "{\n" +
    "  \"timestamp\": \"2019-07-02T13:42:34.090909090+02:00\"\n" +
    "}\n";

// When
TimeTracker tracker = objectMapper.readValue(json, TimeTracker.class);

// Then
assertNotNull(tracker);
assertNotNull(tracker.timestamp);
assertEquals(2019, tracker.timestamp.getYear());
assertEquals(Month.JULY, tracker.timestamp.getMonth());
assertEquals(2, tracker.timestamp.getDayOfMonth());
assertEquals(13, tracker.timestamp.getHour()); // <-- The timezone offset is applied here
assertEquals(42, tracker.timestamp.getMinute());
assertEquals(34, tracker.timestamp.getSecond());
assertEquals(ZoneOffset.ofHours(2), tracker.timestamp.getOffset()); // <-- No offset information, as it is converted to UTC

// Back again
String newJson = objectMapper.writeValueAsString(tracker);
assertEquals(json, newJson); // <-- Of course when converting back it is not the same.

显然,时区偏移量的2小时被计算成小时数,结果是一个utc对象,而不是utc+02:00。这仍然表示相同的时间,因此是正确的。再次转换时,结果当然不同于初始输入:

original: 2019-07-02T13:42:34.090909090+02:00
result:   2019-07-02T11:42:34.09090909Z

在将json字符串转换为 OffsetDateTime ? 我想如果我能做到这一点,那么转换回json将得到相同的值。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题