JDC
JDC

Reputation: 4385

Jackson - Serialize ZonedDateTime to ISO 8601 String

I want to serialize a ZonedDateTime to an ISO 8601 compliant String, e.g.:
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.

Thank you already for your help!

Upvotes: 24

Views: 23859

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

Make sure you include and register the Jackson module for date and time classes introduced in Java 8. E.g.

<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. E.g.

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

Upvotes: 44

Related Questions