介绍
在使用spring boot 2.1.1时,存在日期(Date)类型的数据格式转换不符合项目的要求,还有null对象转换成“null”字符串的问题等,需要自己配置消息转换器。通过网上资料和研究,完成了自定义json消息转换器的实现。
实现
- 首先需要创建一个类,再类上添加注释@Configuration。
- 实现接口WebMvcConfigurer。
- 重载方法configureMessageConverters,然后将自定义json消息转换器添加到默认的消息转换器的列表。
- 代码实现
/**
* spring mvc 配置
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer{
/**
* 配置消息转换
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
List<HttpMessageConverter<?>> result = new ArrayList<>(converters.size() + 2);
//配置json消息转换
FastJsonHttpMessageConverter jsonConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
//List字段如果为null,输出为[],而非null
SerializerFeature.WriteNullListAsEmpty,
//是否输出值为null的字段,默认为false
SerializerFeature.WriteMapNullValue,
//字符串null返回空字符串
SerializerFeature.WriteNullStringAsEmpty,
//空布尔值返回false
SerializerFeature.WriteNullBooleanAsFalse,
//结果是否格式化,默认为false
SerializerFeature.PrettyFormat
);
jsonConverter.setFastJsonConfig(fastJsonConfig);
result.add(jsonConverter);
//配置编码转换
result.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
converters.clear();
converters.addAll(result);
}
}
注:必须将自定义的json消息转换器添加到列表的最前方,直接添加进去是有可能不生效的