引入fastjsonjava
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
配置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
WriteNullListAsEmpty :List字段若是爲null,輸出爲[],而非null
WriteNullStringAsEmpty : 字符類型字段若是爲null,輸出爲"",而非null
DisableCircularReferenceDetect :消除對同一對象循環引用的問題,默認爲false(若是不配置有可能會進入死循環)
WriteNullBooleanAsFalse:Boolean字段若是爲null,輸出爲false,而非null
WriteMapNullValue:是否輸出值爲null的字段,默認爲false。spring
最後響應結果:json