zoukankan      html  css  js  c++  java
  • fastjson格式化输出内容

    引入fastjson

    <!--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配置。

    FastJson SerializerFeatures

    WriteNullListAsEmpty  :List字段如果为null,输出为[],而非null
    WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
    DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
    WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
    WriteMapNullValue:是否输出值为null的字段,默认为false。

    最后响应结果:

  • 相关阅读:
    OC中extern,static,const的用法
    pod install 报错
    设置Image渲染模式使用TintColor
    VLC 用到的那些 YUV 格式
    base64编码原理
    scp 拷贝文件时报错
    linux 恢复误删文件
    hadoop 集群安装(Cloudera CDH方式)
    记录自己需要读的几本书
    求解最长回文子串
  • 原文地址:https://www.cnblogs.com/wangjing666/p/7404492.html
Copyright © 2011-2022 走看看