SpringBoot2.0系列教程(四)Springboot框架自定义消息转换器

Hello大家好,本章我们添加自定义消息转换器。另求各路大神指点,感谢

一:消息转换器能干什么?

不知道大家有没有遇到过这种情况:后台接口返回一个实例,当你需要使用某个属性的值时,你还要判断一下值是否为null;接口返回一堆属性值为null的属性等

ok,消息转换器可以帮你解决这个问题

二:添加fastjson依赖

打开pom.xml,找到<dependencies></dependencies>标签,在标签中添加fastjson依赖

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.22</version>
</dependency>

然后鼠标右键选择Maven→Reimport进行依赖下载

三:创建配置文件

在文件夹configurer中创建WebConfigurer

package com.example.demo.core.configurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/19 10:42
 */
@Configuration
public class WebConfigurer extends WebMvcConfigurationSupport {

    /**
     * 修改自定义消息转换器
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4();
        converter.setSupportedMediaTypes(getSupportedMediaTypes());
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
            // String null -> ""
            SerializerFeature.WriteNullStringAsEmpty,
            // Number null -> 0
            SerializerFeature.WriteNullNumberAsZero,
            //禁止循环引用
            SerializerFeature.DisableCircularReferenceDetect
        );
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

    private List<MediaType> getSupportedMediaTypes() {
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        return supportedMediaTypes;
    }
}
其中
config.setSerializerFeatures()

方法中可以添加多个配置,以下列举出几个常用配置,更多配置请自行百度

WriteNullListAsEmpty  :List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
WriteMapNullValue:是否输出值为null的字段,默认为false

四:数据库中添加测试数据

INSERT INTO `user_info` VALUES ('1', '1');
INSERT INTO `user_info` VALUES ('2', null);

五:测试

查询条件id为2

未配置转换器时,查询结果为

{
    "code": 200,
    "msg": "success",
    "data": {
        "id": 2,
        "userName": null
    }
}

配置转换器之后,查询结果为

{
    "code": 200,
    "data": {
        "id": 2,
        "userName": ""   //这里已经变为"",而不是null
    },
    "msg": "success"
}

项目地址

码云地址: https://gitee.com/beany/mySpringBoot

GitHub地址: https://github.com/MyBeany/mySpringBoot

写文章不易,如对您有帮助,请帮忙点下star

结尾

springboot添加自定义消息转换器已完成,后续功能接下来陆续更新,另求各路大神指点,感谢大家。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值