spring-boot使用fastjson二

pom

 
            com.alibaba
            fastjson
            1.2.46
        

Fastjson的SerializerFeature序列化属性

  • PrettyFormat---------结果是否格式化,默认为false
  • QuoteFieldNames———-输出key时是否使用双引号,默认为true
  • WriteMapNullValue——–是否输出值为null的字段,默认为false
  • WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
  • WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
  • WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
  • WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
  • WriteDateUseDateFormat-Date字段按字符串输出

配置类

package com.ghgcn.chapter01.config;

import com.alibaba.fastjson.serializer.SerializeConfig;
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.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.nio.charset.Charset;
import java.util.List;
@Configuration
public class CustomMVCConfiguration extends WebMvcConfigurerAdapter {


    /**
     * 配置 FastJsonHttpMessageConverter
     * @return
     */
    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){

        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setCharset(Charset.defaultCharset());


        //可变参数,传多个
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.BrowserCompatible,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteDateUseDateFormat);

        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");


        converter.setFastJsonConfig(fastJsonConfig);

        return  converter;

    }


    @Override
    public void configureMessageConverters(List> converters) {
        super.configureMessageConverters(converters);
        //添加FastJsonHttpMessageConverter
        converters.add(fastJsonHttpMessageConverter());

    }
}

{
"message": "执行成功",
"object": {
"birthday": "2018-04-23 17:00:23", //日期有格式化 为指定格式
"gender": null,//null值有输出
"id": 123,
"name": null
},
"status": 200
}

你可能感兴趣的:(spring-boot使用fastjson二)