spring boot 在SpringMVC中使用Jackson并格式化时间
全局配置 全局配置 全局配置 Jackson时间格式化
mvc Jackson 返回时间时,默认会返回时间戳或者是 2018-08-30T12:12:12CST格式的时间字符串
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
配置了以上参数 只能对Date 类型的时间格式化 对于 LocalDateTime ,Instant 并没有什么效果
只需要添加以下配置就可以解决
@Configuration
public class Java8TimeConfig {
@Value("${spring.jackson.date-format}")
private String formatValue;
@Bean(name = "format")
DateTimeFormatter format() {
return DateTimeFormatter.ofPattern(formatValue);
}
@Bean
public ObjectMapper serializingObjectMapper(@Qualifier("format") DateTimeFormatter format) {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(format));
javaTimeModule.addSerializer(Instant.class, new InstantCustomSerializer(format));
javaTimeModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(javaTimeModule);
return mapper;
}
class InstantCustomSerializer extends JsonSerializer<Instant> {
private DateTimeFormatter format;
private InstantCustomSerializer(DateTimeFormatter formatter) {
this.format = formatter;
}
@Override
public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (instant == null) {
return;
}
String jsonValue = format.format(instant.atZone(ZoneId.systemDefault()));
jsonGenerator.writeString(jsonValue);
}
}
}
需要引入相关jar包 下面是pom文件
<!--jackson 时间格式化-->
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>