现在我是使用@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
将 Instant 序列化为字符串的,但是每个地方都要加上。有没有全局设置的方法呢?
@Configuration
public class JacksonConfig {
private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
/**
* https://stackoverflow.com/questions/45662820/how-to-set-format-of-string-for-java-time-instant-using-objectmapper
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return jacksonObjectMapperBuilder ->
jacksonObjectMapperBuilder.serializerByType(Instant.class, new JsonSerializer<Instant>() {
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String str = fmt.format(value);
gen.writeString(str);
}
});
}
}
1
wolfie 2021-03-16 14:27:41 +08:00
|
2
clf 2021-03-16 14:31:52 +08:00 1
下方省略号部分自己填入序列化逻辑。
``` @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() { @Override public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) { jacksonObjectMapperBuilder.serializerByType(Instant.TYPE, ……); jacksonObjectMapperBuilder.serializerByType(Instant.class, ……); } }; return cunstomizer; } ``` |
3
arthas2234 2021-03-16 14:39:31 +08:00
配置文件里面添加
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 |
4
JasonLaw OP |