As I was working on some random data with a ZonedDateTime, it turned out Jackson was unable to deserialize it. How come?

Why not use Jackson datetime module?

The codebase I was working on, did not support the Jackson datetime module. It was also not possible to add this module as all Jackson related code was provided and the vendor stressed very clearly ‘not to mess things up with other versions’.

Writing the Deserializer

So I wrote a simple deserializer. It was actually quite easy: datetime’s wer in the following format: 2020-05-09T23:24:13Z

Luckily the ZonedDateTime offers a static parse method.

So it all comes down to this simple class:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;
import java.time.ZonedDateTime;

public class ZonedDateTimeDeserializer extends StdDeserializer<ZonedDateTime> {
    public ZonedDateTimeDeserializer(){
        this(null);
    }
    protected ZonedDateTimeDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return ZonedDateTime.parse(jsonParser.getText());
    }
}

Using the Deserializer

The field I want to deserialize into, needs an additional annotation:

@JsonDeserialize(using = ZonedDateTimeDeserializer.class)
private ZonedDateTime date;

That’s it! In summary:

  • Write a custom deserializer
  • Use it with the @JsonDeserialize annotation