配置使用FastJson

FastJson是阿里巴巴旗下的一個開源項目之一,專門用來做快速操作Json的序列化與反序列化的組件。

1. 添加依賴

新建項目的過程可以參考使用JPA實現(xiàn)MySQL數(shù)據(jù)庫基本CRUD操作
訪問倉庫地址:https://mvnrepository.com/artifact/com.alibaba/fastjson
選擇最新的版本,注意一定要選最新的版本,否則會出現(xiàn)有些類不支持的情況(我在寫代碼時,遇到了Cannot resolve symbol ‘...’這種提示,換成新版本的依賴就沒問題了,此處著重記錄),當(dāng)然新版本也會淘汰一些,仿照網(wǎng)上寫代碼遇到問題時可以考慮是否被新版本淘汰了。
我當(dāng)時的最新版本為1.2.54

點擊1.2.54,將紅色圈出的依賴復(fù)制粘貼到pom.xml中,再根據(jù)提示import一下
創(chuàng)建使用JPA實現(xiàn)MySQL數(shù)據(jù)庫基本CRUD操作中的結(jié)構(gòu)和代碼,復(fù)制代碼時注意不同項目間的package及import名稱問題

2.配置FastJson

創(chuàng)建FastJsonConfiguration文件,代碼如下

package com.example;

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.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * Created by conan on 2019/1/7.
 */
@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
    {
        //調(diào)用父類配置
        super.configureMessageConverters(converters);
        //創(chuàng)建消息轉(zhuǎn)換器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //創(chuàng)建配置類
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //返回內(nèi)容的過濾
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //將fastjson添加到視圖消息轉(zhuǎn)換器列表內(nèi)
        converters.add(fastConverter);
    }
}

FastJson SerializerFeatures配置:
WriteMapNullValue:是否輸出值為null的字段;
WriteNullListAsEmpty:List字段如果為null,輸出為[],而非null;
WriteNullStringAsEmpty: 字符類型字段如果為null,輸出為"",而非null;
DisableCircularReferenceDetect:消除對同一對象循環(huán)引用的問題,默認(rèn)為false(如果不配置有可能會進(jìn)入死循環(huán));
WriteNullBooleanAsFalse:Boolean字段如果為null,輸出為false,而非null。

3.配置效果

數(shù)據(jù)庫新建一行GroupName值為null的數(shù)據(jù)

啟動本程序
訪問地址:http://127.0.0.1:8080/user/list
網(wǎng)頁看到的結(jié)果為
更改FastJson配置

        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

重新啟動程序,刷新網(wǎng)頁,結(jié)果變?yōu)?div id="u0z1t8os" class="image-package">

FastJson配置生效。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容