fastjson格式化輸出內容

引入fastjsonjava

<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>

咱們接下來建立一個 FastJsonConfiguration配置信息類,添加 @Configuration註解讓SpringBoot自動加載類內的配置,有一點要注意咱們繼承了 WebMvcConfigurerAdapter這個類,這個類是SpringBoot內部提供專門處理用戶自行添加的配置,裏面不單單包含了修改視圖的過濾還有其餘不少的方法,包括咱們後面章節要講到的攔截器,過濾器,Cors配置等。
fastJson視圖過濾配置詳細內容以下圖5所示:


配置fastjson類
package com.example.demo.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.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
* Created by BFD-593 on 2017/8/21.
*/
@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();
     JSONObject.DEFFAULT_DATE_FORMAT="yyyy-MM-dd";//設置自定義日期格式(默認是yyyy-MM-dd HH:mm:ss)

//修改配置返回內容的過濾
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
          SerializerFeature.WriteDateUseDateFormat,//設置使用自定義日期格式,這樣全部序列化的日期就會按指定格式序列化

//開發環境調試使用,線上環境請取消,僅是格式化輸出json設置,會輸出太多無用空格
SerializerFeature.PrettyFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//將fastjson添加到視圖消息轉換器列表內
converters.add(fastConverter);
}
}

咱們來介紹下經常使用的SerializerFeatures配置。web

FastJson SerializerFeatures

WriteNullListAsEmpty  :List字段若是爲null,輸出爲[],而非null
WriteNullStringAsEmpty : 字符類型字段若是爲null,輸出爲"",而非null
DisableCircularReferenceDetect :消除對同一對象循環引用的問題,默認爲false(若是不配置有可能會進入死循環)
WriteNullBooleanAsFalse:Boolean字段若是爲null,輸出爲false,而非null
WriteMapNullValue:是否輸出值爲null的字段,默認爲false。spring

最後響應結果:json

相關文章
相關標籤/搜索