SpringBoot2.0整合fastjson的正確姿勢


        SpringBoot2.0如何集成fastjson?在網上查了一堆資料,但是各文章的說法不一,有些還是錯的,可能只是簡單測試一下就認為ok了,最后有沒生效都不知道。恰逢公司項目需要將JackSon換成fastjson,因此自己來實踐一下SpringBoot2.0和fastjson的整合,同時記錄下來方便自己后續查閱。

一、Maven依賴說明

    SpringBoot的版本為: <version>2.1.4.RELEASE</version>
    在pom文件中添加fastjson的依賴:
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>


二、整合

        我們寫一個配置類WebConfig實現WebMvcConfigurer接口 ,然后重寫 configureMessageConverters方法。具體的代碼如下:
package com.psx.gqxy.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;

/**
 * web相關的定制化配置
 * @author ZENG.XIAO.YAN
 * @version 1.0
 * @Date 9012-88-88
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    // WebMvcConfigurerAdapter 這個類在SpringBoot2.0已過時,官方推薦直接實現WebMvcConfigurer 這個接口

    /**
     * 使用fastjson代替jackson
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        /*
         先把JackSon的消息轉換器刪除.
         備注: (1)源碼分析可知,返回json的過程為:
                    Controller調用結束后返回一個數據對象,for循環遍歷conventers,找到支持application/json的HttpMessageConverter,然后將返回的數據序列化成json。
                    具體參考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
               (2)由於是list結構,我們添加的fastjson在最后。因此必須要將jackson的轉換器刪除,不然會先匹配上jackson,導致沒使用fastjson
        */
        for (int i = converters.size() - 1; i >= 0; i--) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.remove(i);
            }
        }
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        //自定義fastjson配置
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                SerializerFeature.WriteMapNullValue,        // 是否輸出值為null的字段,默認為false,我們將它打開
                SerializerFeature.WriteNullListAsEmpty,     // 將Collection類型字段的字段空值輸出為[]
                SerializerFeature.WriteNullStringAsEmpty,   // 將字符串類型字段的空值輸出為空字符串
                SerializerFeature.WriteNullNumberAsZero,    // 將數值類型字段的空值輸出為0
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect    // 禁用循環引用
        );
        fastJsonHttpMessageConverter.setFastJsonConfig(config);

        // 添加支持的MediaTypes;不添加時默認為*/*,也就是默認支持全部
        // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes為application/json
        // 參考它的做法, fastjson也只添加application/json的MediaType
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        converters.add(fastJsonHttpMessageConverter);
    }
}


三、測試

         (1)代碼
        要測試fastjson是否整合成功的話,我們只需要在實體類中使用一下fastjson的注解就ok。如果注解生效了,說明fastjson整合成功了。直接看代碼
package com.psx.gqxy.web.controller;

import com.alibaba.fastjson.annotation.JSONField;
import com.psx.gqxy.common.base.ModelResult;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;

/**
 * TestController
 * @author ZENG.XIAO.YAN
 * @version 1.0
 * @Date 9012-88-88
 */
@RestController
public class TestController {

    @GetMapping("/json")
    public ModelResult<JsonBean> testJson() {
        ModelResult<JsonBean> result = new ModelResult<>();
        JsonBean jsonBean = new JsonBean();
        jsonBean.setBirthDay(new Date());
        jsonBean.setName("測試");
        result.setData(jsonBean);
        // 效果
        /*{
            "code": "200",
                "data": {
            "birthDay": "2019年05月12日",
                    "name": "測試",
                    "qqList": []
        },
            "msg": ""
        }*/
        return result;
    }


    @Data
    class JsonBean {
        private String name;
        @JSONField(format = "yyyy年MM月dd日")
        private Date birthDay;
        private List<String> qqList;
    }
}
         (2)效果
                 


        通過這個2步的測試,發現fastjson的注解生效了,也就說明整合成功了

四、雜談

    SpringBoot2.0后,有些東西改變了。在SpringBoot 1.X時代,整合fastjson是可以不排除JackSon消息轉換器的。但在SpringBoot2.X時代,必須要排除JackSon消息轉換器。

              
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM