Spring Boot整合fastjson

时间:2025-04-24 08:15:58

一、概述

SpringBoot在构建restfult风格的web服务时,默认使用的是Jackson作为JSON解析器,个人使用比较习惯的 json 框架是 fastjson,所以SpringBoot默认的 json 使用起来就很陌生了,如何使用 fastjson 进行 json 解析呢?

引入依赖

注意,1.2.61以下有严重高危漏洞,1.2.61修复,必须升级到1.2.61,目前最新版本为1.2.62

<dependency>
    <groupId></groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>

二、版本

第一种方法:通过extends WebMvcConfigurerAdapter并重写configureMessageConverters方法来实现。

import ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
@MapperScan("")
@SpringBootApplication(scanBasePackages= {"",""})
public class HelloSpringBootApplication extends WebMvcConfigurerAdapter{
 
 
 
 @Override
 public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  
  //创建FastJson的消息转换器
  FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
  //创建FastJson的配置对象
  FastJsonConfig config = new FastJsonConfig();
  //对Json数据进行格式化
  ();
  (config);
  (convert);
 }
 
 
 
 public static void main(String[] args) {
  
  (, args);
 }
 
}

第二种方法:在项目启动类中通过@Bean注解处理

 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
@MapperScan("")
@SpringBootApplication(scanBasePackages= {"",""})
public class HelloSpringBootApplication
{
 @Bean
 public HttpMessageConverters fastJsonMessageConverter() {
  
    //创建FastJson的消息转换器
    FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
    //创建FastJson的配置对象
    FastJsonConfig config = new FastJsonConfig();
    //对Json数据进行格式化
    ();
    (config);
    HttpMessageConverter<?> con =convert;
    return new HttpMessageConverters(con);
 }
 
 public static void main(String[] args) {
  
  (, args);
 }
 
}

三、SpringBoot2.0版本

自定义配置类implements WebMvcConfigurer 类

import ;
import ;
import ;
import ;
import ;
import ;
import .MappingJackson2HttpMessageConverter;
import ;

import ;
import ;

@Configuration
public class JsonConfig implements WebMvcConfigurer {
    /**
     * 使用fastjson代替jackson
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        /*
         先把JackSon的消息转换器删除.
         备注: (1)源码分析可知,返回json的过程为:
                    Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
                    具体参考的writeWithMessageConverters方法
               (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
        */
        for (int i = () - 1; i >= 0; i--) {
            if ((i) instanceof MappingJackson2HttpMessageConverter) {
                (i);
            }
        }
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        //自定义fastjson配置
        FastJsonConfig config = new FastJsonConfig();
        (
                ,        // 是否输出值为null的字段,默认为false,我们将它打开
                ,     // 将Collection类型字段的字段空值输出为[]
                ,   // 将字符串类型字段的空值输出为空字符串
                ,    // 将数值类型字段的空值输出为0
                ,
                    // 禁用循环引用
        );
        (config);

        // 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
        // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
        // 参考它的做法, fastjson也只添加application/json的MediaType
        List<MediaType> fastMediaTypes = new ArrayList<>();
        (MediaType.APPLICATION_JSON_UTF8);
        (fastMediaTypes);
        (fastJsonHttpMessageConverter);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> messageConverter : converters) {
            ("=====================" + messageConverter);
        }
    }
}

测试

@RestController
public class TestController {
    @RequestMapping("/test")
    public Object test() {
        User user = new User();
         = new Date();
         = "张三";
        return user;
    }
}

public class User {
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    public Date date;
    public String name;
}