Spring-boot系列(6):整合fastjson訊息檢視配置
阿新 • • 發佈:2019-02-18
通過fashjson訊息檢視配置可以控制json返回的情況,例如:資料該欄位為空,返回前端值預設是null,可以使用WriteNullListAsEmpty 改為”“。
springboot整合
在原來專案上增加
- 依賴
<!--引入fastjson依賴-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency >
- 增加配置FastJsonConfiguration
@Configuration
public class FastJsonConfiguration extends WebMvcConfigurerAdapter
{
/**
* 修改自定義訊息轉換器
* @param converters 訊息轉換器列表
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//呼叫父類的配置
super.configureMessageConverters(converters);
//建立fastJson訊息轉換器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//建立配置類
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//修改配置返回內容的過濾
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//將fastjson新增到檢視訊息轉換器列表內
converters.add(fastConverter);
}
}
FastJson SerializerFeatures
WriteNullListAsEmpty :List欄位如果為null,輸出為[],而非null
WriteNullStringAsEmpty : 字元型別欄位如果為null,輸出為”“,而非null
WriteMapNullValue:是否輸出值為null的欄位,預設為false。
WriteNullBooleanAsFalse:Boolean欄位如果為null,輸出為false,而非null
DisableCircularReferenceDetect :消除對同一物件迴圈引用的問題,預設為false(如果不配置有可能會進入死迴圈)
在主方法增加註解@EnableAutoConfiguration