Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize "Zulu" time in ISO8601 format in jackson

I have a need to de-serialize time of format 2016-11-28T10:34:25.097Z using Jackson into ZonedDateTime of Java8.

I believe I correctly configured ObjectMapper (a factory method):

 @Bean
ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    // some other config...
    objectMapper.registerModule(new JavaTimeModule());
    return objectMapper;
}

And I have in my code for DTO a field

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

when I try to parse this by Jackson, I get

 java.lang.IllegalArgumentException: Can not deserialize value of type java.time.ZonedDateTime 
 from String "2016-11-28T10:34:25.097Z": Text '2016-11-28T10:34:25.097Z' could not be parsed,
 unparsed text found at index 23  at [Source: N/A; line: -1, column: -1]  

Without @JsonFormat problem remains.

How I could possibly overcome this?

like image 279
onkami Avatar asked Mar 11 '23 13:03

onkami


2 Answers

The problem is probably with 'Z' in the pattern. It does not allow literal 'Z' in the date time value. Try 'X' instead.

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")
like image 87
pkalinow Avatar answered Mar 15 '23 03:03

pkalinow


I needed to serialize/deserialize a date in ISO8601 Zulu format 2016-11-28T10:34:25.097Z like you

I chose to change the date formatter in ObjectMapper using ISO8601DateFormat

like this

@Bean
ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    // some other config...
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setDateFormat(new ISO8601DateFormat());
    return objectMapper;
}
like image 42
Quentin Avatar answered Mar 15 '23 05:03

Quentin