从零搭建本身的SpringBoot后台框架(四)

Hello你们好,本章咱们添加自定义消息转换器。有问题能够联系我mr_beany@163.com。另求各路大神指点,感谢

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

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

ok,消息转换器能够帮你解决这个问题git

二:添加fastjson依赖

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

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.22</version>
</dependency>复制代码

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

三:建立配置文件

在文件夹configurer中建立WebConfigurerspring

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()复制代码

方法中能够添加多个配置,如下列举出几个经常使用配置,更多配置请自行百度json

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为2springboot

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

{
    "code": 200,
    "msg": "success",
    "data": {
        "id": 2,
        "userName": null
    }
}复制代码

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

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

项目地址

码云地址: gitee.com/beany/mySpr…

GitHub地址: github.com/MyBeany/myS…

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

结尾

springboot添加自定义消息转换器已完成,后续功能接下来陆续更新,有问题能够联系我mr_beany@163.com。另求各路大神指点,感谢你们。

相关文章
相关标签/搜索