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
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é)果為
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
重新啟動程序,刷新網(wǎng)頁,結(jié)果變?yōu)?div id="u0z1t8os" class="image-package">