Springboot配合使用FastJson

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuxin132133/article/details/83537923

说明:Springboot默认返回实体类或者集合时,使用的是Json格式,利用jackson进行解析,现在我们利用阿里巴巴提供的FastJson覆盖掉springboot默认的封装方法,使得返回数据为fastJson格式

1.添加Maven依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>

2.配置使用fastJson返回json视图

package com.song.util.fastJson;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

public class FastJsonConfiguration extends WebMvcConfigurerAdapter {

public void configureMessageConvert(List<HttpMessageConverter<?>> converters){
    //调用父类配置
    super.configureMessageConverters(converters);
    //创建fastJson消息转换器
    FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
    //创建配置类
    FastJsonConfig fastJsonConfig=new FastJsonConfig();
    //修改配置返回内容的过滤
    fastJsonConfig.setSerializerFeatures(
         /*   FastJson SerializerFeatures
            WriteNullListAsEmpty  :List字段如果为null,输出为[],而非null
    WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
    DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
    WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
    WriteMapNullValue:是否输出值为null的字段,默认为false。*/

            SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteMapNullValue
    );
    fastConverter.setFastJsonConfig(fastJsonConfig);
    //将fastJson添加到视图消息转换器列表内
    converters.add(fastConverter);
}

}

3.controller层

发送get请求:   localhost:8081/request/name?name=柯南

获取数据: [{"id":9,"name":"柯南","age":12,"address":""}]   

数据库中address为null,fastJson默认返回空字符串

猜你喜欢

转载自blog.csdn.net/xuxin132133/article/details/83537923