Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Serialize ZonedDateTime to ISO 8601 String

Tags:

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!

like image 804
JDC Avatar asked Feb 14 '18 07:02

JDC


People also ask

How does Jackson serialize date?

It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).

How does Jackson deserialize dates from JSON?

This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);

Is ObjectMapper thread safe?

Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.

How do I change the date format in ObjectMapper?

We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.


1 Answers

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);
like image 191
Manos Nikolaidis Avatar answered Sep 21 '22 17:09

Manos Nikolaidis