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!
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).
This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With