简体   繁体   English

Jackson-将ZonedDateTime序列化为ISO 8601字符串

[英]Jackson - Serialize ZonedDateTime to ISO 8601 String

I want to serialize a ZonedDateTime to an ISO 8601 compliant String, eg: 我想将ZonedDateTime序列化为符合ISO 8601的字符串,例如:
2018-02-14T01:01:02.074+0100 . 2018-02-14T01:01:02.074+0100

I tried the following: 我尝试了以下方法:

@JsonProperty("@timestamp")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private ZonedDateTime timestamp;

But unfortunately it does not give the correct result and serializes the ZonedDateTime with all its fields, etc. 但是不幸的是,它没有给出正确的结果,并且将ZonedDateTime及其所有字段序列化, ZonedDateTime

Thank you already for your help! 已经感谢您的帮助!

Make sure you include and register the Jackson module for date and time classes introduced in Java 8. Eg 确保为Java 8中引入的日期和时间类包括并注册Jackson模块。

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.8.10</version>
</dependency>

and if necessary: 并在必要时:

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

Side note: You may also achieve the desired format without the annotation and just configuring ObjectMapper to not serialize date as timestamp. 旁注:您也可以不使用注释而仅将ObjectMapper配置为不将日期序列化为时间戳来获得所需的格式。 Eg 例如

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM