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

相关文章
相关标签/搜索