springboot将LocalDateTime转为时间戳
springboot在启动的时候会自动给我们注入一个objectMapper。
但是这个objectMapper并没有对LocalDateTime类进行特殊的序列化处理,当我想将其转为时间戳的时候,只能自己实现一个序列化类,并将需要转换的实体类字段上添加注解@JsonSerialize(using = LocalDateTimeSerialize.class)
public class LocalDateTimeSerialize extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
long timestamp = getTimestamp(value);
gen.writeString(String.valueOf(timestamp));
}
private long getTimestamp(LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
}
}
但缺点也很显而易见:这样每个字段上面都添加注解麻烦又难以维护
所以还是需要看看能不能直接改objectMapper配置的地方,查阅了网上的资料发现大多是自己重新注入一个自定义的objectMapper
@Configuration
public class JacksonConfig{
@Bean
public ... // 可以自己搜索
}
如果不需要springboot默认配置的objectMapper,那自然没问题,也推荐这么做。
但如果想直接在默认配置上直接修改:
- 修改
application.yml
文件 - 实现
Jackson2ObjectMapperBuilderCustomizer
接口进行修改
对于LocalDateTime自定义序列化的方法第一点我没找到什么配置可以直接修改,选择第二种方法
@Configuration
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerialize());
}
}
jackson研究的不深,还需多多努力