@Configuration
public class JacksonConfiguration {
/**
* DateTime格式化字符串
*/
private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* Date格式化字符串
*/
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
/**
* Time格式化字符串
*/
private static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";
private static final String DEFAULT_TIME_ZONE = "GMT+8";
/**
* Jackson序列化和反序列化转换器,用于转换Post请求体中的json以及将对象序列化为返回响应的json
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
DateFormat dateTimeDf = DateUtil.newSimpleFormat(DEFAULT_DATETIME_PATTERN, Locale.CHINA, TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
DateTimeFormatter dateTimeDtf = DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN).withZone(ZoneId.of(DEFAULT_TIME_ZONE));
DateTimeFormatter dateDtf = DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN).withZone(ZoneId.of(DEFAULT_TIME_ZONE));
DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN).withZone(ZoneId.of(DEFAULT_TIME_ZONE));
return builder -> builder
.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeDtf))
.serializerByType(LocalDate.class, new LocalDateSerializer(dateDtf))
.serializerByType(LocalTime.class, new LocalTimeSerializer(timeDtf))
.serializerByType(Date.class, new DateSerializer(false, dateTimeDf))
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeDtf))
.deserializerByType(LocalDate.class, new LocalDateDeserializer(dateDtf))
.deserializerByType(LocalTime.class, new LocalTimeDeserializer(timeDtf))
.deserializerByType(Date.class, new DateDeserializers.DateDeserializer(DateDeserializers.DateDeserializer.instance, dateTimeDf, DEFAULT_DATETIME_PATTERN))
.serializerByType(Long.TYPE, ToStringSerializer.instance)
.serializerByType(Long.class, ToStringSerializer.instance);
}
}