spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
方式2,使用@JsonFormat
> 相信这种方式大家都知道,就是在传输的Bean对象属性上加上 @JsonFormat 注解
@Data
public class TestBO {
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date date;
private LocalDateTime localDateTime;
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyyMMdd")
private LocalDate localDate;
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "HHmmss")
private LocalTime localTime;
}
方式3,配置全局格式化的类
直接上代码,可自己定义任何的类型,当然也可以使用网上说的那个@JsonComponent注解代替@Configuration
@Configuration
public class JacksonDateformatConfig {
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String TIME_FORMAT = "HH:mm:ss";
@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)))
.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)))
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)))
.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)))
.serializerByType(Date.class, new DateSerializer(true, new SimpleDateFormat(DATETIME_FORMAT))).deserializerByType(Date.class, new JsonDeserializer() {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return p.getValueAsString();
}
}).deserializerByType(BigDecimal.class, new NumberDeserializers.BigDecimalDeserializer());
}
}
@JsonFormat 注解的优先级比较高,会以 @JsonFormat 注解的时间格式为主。



