Jackson deserialization issue for ZonedDateTime

tunix picture tunix · Jan 13, 2016 · Viewed 25k times · Source

I've the following field in a class I use during deserialization of a service that I'm consuming.

private ZonedDateTime transactionDateTime;

The service I'm consuming may return a Date or DateTime using the pattern: yyyy-MM-dd'T'HH:mm:ss.SSSZ

Let me give 2 examples of what the service returns:

  • 2015-11-18T18:05:38.000+0200
  • 2015-11-18T00:00:00.000+0200

While first one works well, the latter causes the following exception to be thrown during deserialization:

java.time.format.DateTimeParseException: Text '2015-11-18T00:00:00.000+0200' could not be parsed at index 23

I'm using;

  • Spring Boot 1.3.1
  • Jackson 2.6.4 (with JSR310 module included)

Does this require a custom deserialization class?

Answer

Ricardo Vila picture Ricardo Vila · Jan 13, 2016

You can use annotations like:

@JsonSerialize(using = MyCustomJsonDateSerializer.class)

or

@JsonDeserialize(using = MyCustomJsonDateDeserializer.class)

To customize how Jackson parses Dates. Those custom Serializer and Deserializer must extend JsonSerializer and JsonDeserializer. For example:

public class MyCustomJsonDateSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date date, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString(date != null ? ISODateTimeFormat.dateTime().print(new DateTime(date)) : null);
      }
}