我正在尝试通过添加以下配置来将LocalDateTime
序列化为TimeStamp。但是它不起作用。我正在使用 jackson-datatype-jsr310 支持Java 8 date /时间数据类型。
@Configuration
@Slf4j
public class JacksonConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return (Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) -> {
jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer());
jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer());
};
}
public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
final String localDate = p.getText().trim();
log.info("Deserialize");
JavaTimeModule javaTimeModule = new JavaTimeModule();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(javaTimeModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
if (NumberUtils.isParsable(localDate)) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(localDate)), TimeZone.getDefault().toZoneId()).withNano(0);
}
return LocalDateTime.parse(localDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
public final DateTimeFormatter DT_PATTERN = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void serialize(LocalDateTime value, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
log.info("Serialize");
jgen.writeString(value.format(DT_PATTERN));
}
}
}
当我解析LocalDateTime
时,我得到{2016,12,21,15,53,57,178}
而不是1482306837178
。
这是我的测试模型类Foo
public class Foo{
private String name;
private LocalDateTime creation_time;
}