Spring Boot 自定义json消息转换器(配置消息转换器)

Spring Boot 自定义json消息转换器

介绍

在使用spring boot 2.1.1时,存在日期(Date)类型的数据格式转换不符合项目的要求,还有null对象转换成“null”字符串的问题等,需要自己配置消息转换器。通过网上资料和研究,完成了自定义json消息转换器的实现。

实现

  1. 首先需要创建一个类,再类上添加注释@Configuration
  2. 实现接口WebMvcConfigurer
  3. 重载方法configureMessageConverters,然后将自定义json消息转换器添加到默认的消息转换器的列表。
  4. 代码实现
/**
 * 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消息转换器添加到列表的最前方,直接添加进去是有可能不生效的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值