The following solution solves the task of serialize/deserialise the LocalDateTime
to the timestamp and relevant at least for spring-boot v1.5 and also includes next points that are not taken into account in the @xingbin's answer:
- If there is a necessity to have the same behaviour as for
java.util.Date
have to use the toInstant().toEpochMilli()
instead the toInstant().getEpochSecond()
- Check on
null
the value to deserialize
- And optional point: specify this serialization/deserialization configuration for the Jackson
ObjectMapper
The timestamp serializer class:
public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public LocalDateTimeSerializer() {
super(LocalDateTime.class);
}
@Override
public void serialize(final LocalDateTime value,
final JsonGenerator generator,
final SerializerProvider provider) throws IOException {
if (value != null) {
final long mills = value.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
generator.writeNumber(mills);
} else {
generator.writeNull();
}
}
}
The timestamp deserializer class:
public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public LocalDateTimeDeserializer() {
super(LocalDateTime.class);
}
@Override
public LocalDateTime deserialize(final JsonParser parser,
final DeserializationContext context) throws IOException {
final long value = parser.getValueAsLong();
return LocalDateTime.ofInstant(Instant.ofEpochMilli(value), DEFAULT_ZONE_ID);
}
}
The object mapper configuration:
@Configuration
public class ObjectMapperConfiguration {
@Bean
public ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
objectMapper.registerModule(module);
return objectMapper;
}
}