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
.
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?
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