SpringBoot系列---【统一解决LocalDate和LocalDateTime响应结果格式化的问题】
直接上代码
@Configuration public class CommonConfig { private static final String patternDateTime = "yyyy-MM-dd HH:mm:ss"; private static final String patternDate = "yyyy-MM-dd"; /** * Jackson全局转化long类型为String,解决jackson序列化时传入前端Long类型缺失精度问题 */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return jacksonObjectMapperBuilder -> { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(patternDateTime); DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(patternDate); //返回时间数据序列化 jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter)); //接收时间数据反序列化 jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter)); jacksonObjectMapperBuilder.serializerByType(LocalDate.class, new LocalDateSerializer(dateFormatter)); //接收时间数据反序列化 jacksonObjectMapperBuilder.deserializerByType(LocalDate.class, new LocalDateDeserializer(dateFormatter)); jacksonObjectMapperBuilder.serializerByType(BigInteger.class, ToStringSerializer.instance); jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance); }; } @Bean public RedisTemplatemyRedisTemplate(JedisConnectionFactory factory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // 设置 Key 和 Value 的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // 初始化 RedisTemplate 序列化完成 redisTemplate.afterPropertiesSet(); return redisTemplate; } }