目录
原因:
最近遇到的问题,重新搭建java项目的时候没有发现这个问题,同事使用的时候发现的问题,现在记录一下解决的过程,
使用fastjson解决乱码
解决代码:
@Configuration
public class FastJsonConfig {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
//用字段名作为序列化和反序列化的key值
TypeUtils.compatibleWithFieldName = true;
//指定时区
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
//替换springboot的json框架为fastjson
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
com.alibaba.fastjson.support.config.FastJsonConfig fastJsonConfig = new com.alibaba.fastjson.support.config.FastJsonConfig();
// 空值特别处理
// WriteNullListAsEmpty 将Collection类型字段的字段空值输出为[]
// WriteNullStringAsEmpty 将字符串类型字段的空值输出为空字符串 ""
// WriteNullNumberAsZero 将数值类型字段的空值输出为0
// WriteNullBooleanAsFalse 将Boolean类型字段的空值输出为false
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero,SerializerFeature.WriteNullBooleanAsFalse);
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
}