Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: deserialize epoch to LocalDate

I have following JSON:

{
      "id" : "1",
      "birthday" : 401280850089
}

And POJO class:

public class FbProfile {
    long id;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    LocalDate birthday;
}

I am using Jackson to do deserialization:

public FbProfile loadFbProfile(File file) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    FbProfile profile = mapper.readValue(file, FbProfile.class);
    return profile;
}

But it throws an exception:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (VALUE_NUMBER_INT), expected VALUE_STRING: Expected array or string.

How can I deserialize epoch to LocalDate? I would like to add that if I change the datatype from LocalDate to java.util.Date it works perfectly fine. So maybe it's better to deserialize to java.util.Date and create the getter and setter which will do the conversion to/from LocalDate.

like image 651
kpater87 Avatar asked Jun 07 '17 20:06

kpater87


1 Answers

I've managed to do it writing my own deserializer (thank you @Ole V.V. to point me to the post Java 8 LocalDate Jackson format):

public class LocalDateTimeFromEpochDeserializer extends StdDeserializer<LocalDateTime> {

    private static final long serialVersionUID = 1L;

    protected LocalDateTimeFromEpochDeserializer() {
        super(LocalDate.class);
    }

    @Override
    public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        return Instant.ofEpochMilli(jp.readValueAs(Long.class)).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

}

Notice about timezone is also very useful. Thank you!

The still open question is if it can be done without writing own deserializer?

like image 93
kpater87 Avatar answered Oct 03 '22 00:10

kpater87