首页 > 解决方案 > Jackson OffsetDateTime 序列化 Z 而不是 +00:00 时区?

问题描述

我正在使用带有以下 ObjectMapper 的 Spring Boot:

@Bean
public ObjectMapper objectMapper()
{
    final ObjectMapper mapper = new ObjectMapper();

    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);  
    mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); // Makes no difference to output

    mapper.findAndRegisterModules();

    return mapper;
}

当 OffsetDateTimes 被序列化并在响应中返回时,它们的格式如下:

"2020-02-28T12:28:29.01Z"
"2020-02-28T12:36:21.885Z"

我本来希望最后的时区信息看起来像这样:

"2020-02-28T10:41:25.287+00:00"

这里有什么我遗漏或做错的事情,或者无论如何我可以将时区信息序列化为+00:00格式而不是885Z格式?

非常感谢!

标签: javajsondatejackson

解决方案


使用预构建格式或为DateTimeFormatter.

看看这些(非常简单的)例子:

public static void main(String[] arguments) {
    Instant now = Instant.now();
    
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, ZoneId.of("UTC"));
    OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(now, ZoneId.of("UTC"));
    
    System.out.println(zonedDateTime.toString());
    System.out.println(offsetDateTime.toString());
    System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    System.out.println(zonedDateTime.format(
            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
    );
    System.out.println(offsetDateTime.format(
            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx")
        )
    );
}

我认为您所期望的是最后一个,以 结尾的模式xxx,这导致偏移量始终以 形式显示HH:mm,代码示例的输出是:

2020-02-28T12:49:02.388Z[UTC]
2020-02-28T12:49:02.388Z
2020-02-28T12:49:02.388Z[UTC]
2020-02-28T12:49:02.388Z
2020-02-28T12:49:02+0000
2020-02-28T12:49:02+00:00

推荐阅读