美文网首页
SpringBoot2 - FastJson

SpringBoot2 - FastJson

作者: 朱穆朗玛 | 来源:发表于2018-06-20 15:58 被阅读0次

简介

FastJson是阿里巴巴旗下的一个开源项目,是Json序列化与反序列化组件。

添加FastJson依赖

通过maven仓库获得jar包依赖
访问http://mvnrepository.com/artifact/com.alibaba/fastjson选择1.2.47,复制maven内容到pom.xml

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

创建FastJsonConfiguration配置信息类

package com.gala.jpa;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        
        // 创建配置类
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse);
        
        // 创建消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        fastConverter.setFastJsonConfig(config);
        
        converters.add(fastConverter);
    }

}

FastJson SerializerFeatures常用配置

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

相关文章

网友评论

      本文标题:SpringBoot2 - FastJson

      本文链接:https://www.haomeiwen.com/subject/zrlxyftx.html