使用阿里巴巴 Fastjson 替代 Spring Boot 默认的 Jackson

简介: 本文介绍在 Spring Boot 项目中如何替换默认的 Jackson,集成阿里巴巴 Fastjson 作为 JSON 处理框架。内容涵盖 Fastjson 与 Jackson 的核心对比、依赖配置、自定义消息转换器、null 值统一处理及循环引用控制,并提供安全建议与最佳实践,助你高效、安全地使用 Fastjson。

在 Spring Boot 项目中,默认使用 Jackson 作为 JSON 序列化/反序列化框架。但很多国内团队(尤其是阿里系生态)更倾向于使用 阿里巴巴开源的 Fastjson。本节将详细介绍:

  • Fastjson 与 Jackson 的核心对比;
  • 如何在 Spring Boot 中集成 Fastjson;
  • 如何统一处理 null 值等常见需求。

1. Fastjson 与 Jackson 对比

对比项 Fastjson(阿里巴巴) Jackson(Spring 默认)
上手难度 ⭐ 简单,API 直观 中等,需理解注解体系
文档支持 ✅ 官方提供中文文档 英文为主,社区丰富
性能 略快(尤其小对象) 极快,高并发下更稳定
高级特性 基础功能完善 ✅ 支持泛型、自定义序列化器、模块扩展等
生态整合 需手动配置 Spring ✅ 与 Spring Boot 深度集成
安全性 历史版本存在反序列化漏洞(需用新版) 安全性较高,更新及时

💡 选型建议

  • 若项目已使用 Fastjson 或团队熟悉其 API,可继续使用;
  • 若追求长期维护性、微服务生态兼容性,推荐 Jackson
  • 注意:Fastjson 1.2.83+ 已修复多数安全问题,务必使用较新版本。

2. 在 Spring Boot 中集成 Fastjson

2.1 添加 Maven 依赖

pom.xml 中引入 Fastjson(推荐使用较新稳定版,如 1.2.83,而非过时的 1.2.35):

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version> <!-- 使用最新安全版本 -->
</dependency>

🔒 安全提示:Fastjson 早期版本(<1.2.68)存在严重反序列化漏洞,请务必升级!


2.2 配置 Fastjson 为默认 JSON 转换器

Spring Boot 默认使用 Jackson 的 HttpMessageConverter。要切换为 Fastjson,需自定义配置类:

✅ 正确做法:继承 WebMvcConfigurer推荐

⚠️ 注意:不要继承 WebMvcConfigurationSupport,否则会禁用 Spring Boot 的自动 Web 配置(如静态资源、拦截器等失效)!

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.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 创建 Fastjson 配置对象
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
            SerializerFeature.WriteMapNullValue,         // 保留 Map 中值为 null 的字段
            SerializerFeature.WriteNullStringAsEmpty,    // String null → ""
            SerializerFeature.WriteNullNumberAsZero,     // Number null → 0
            SerializerFeature.WriteNullListAsEmpty,      // List null → []
            SerializerFeature.WriteNullBooleanAsFalse,   // Boolean null → false
            SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用检测(避免 $ref)
        );
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        // 设置支持的媒体类型
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(supportedMediaTypes);
        // 将 Fastjson 转换器添加到 converters 列表首位(优先使用)
        converters.add(0, converter);
    }
}

关键点说明

  • 实现 WebMvcConfigurer 接口,不会覆盖 Spring Boot 自动配置
  • converters.add(0, converter):将 Fastjson 转换器置于列表最前,确保优先使用;
  • DisableCircularReferenceDetect:避免对象循环引用时生成 $ref 字段。

3. 验证 Fastjson 是否生效

复用第 02 课的 JsonController,返回包含 null 的数据:

@RequestMapping("/map")
public Map<String, Object> getMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("name", null);
    map.put("age", (Integer) null);
    map.put("hobby", (List<String>) null);
    map.put("married", (Boolean) null);
    return map;
}

预期返回结果(Fastjson 配置后)

{
  "name": "",
  "age": 0,
  "hobby": [],
  "married": false
}

✅ 所有 null 均按配置转换为默认值,且无 $ref 循环引用标记。


4. 补充:全局关闭循环引用(可选)

若不想在每个配置中写 DisableCircularReferenceDetect,也可通过系统属性全局关闭:

// 在启动类 main 方法中添加(不推荐,影响全局)
System.setProperty("fastjson.compatibleWithJavaBean", "true");
// 或
ParserConfig.getGlobalInstance().setAutoTypeSupport(true); // 谨慎开启!

⚠️ 强烈建议:仅在必要时局部关闭循环引用,避免安全风险。


5. 总结

步骤 操作
1️⃣ 引入 Fastjson 依赖(使用安全版本)
2️⃣ 创建配置类,实现 WebMvcConfigurer
3️⃣ 配置 FastJsonHttpMessageConverter 并设置 SerializerFeature
4️️⃣ 将转换器加入 converters 列表首位
5️⃣ 测试 null 处理与循环引用行为

📌 最佳实践

  • 优先考虑 Jackson,除非有强依赖 Fastjson 的历史原因;
  • 若必须使用 Fastjson,请升级到最新版并严格配置安全策略;
  • 不要继承 WebMvcConfigurationSupport,以免破坏 Spring Boot 自动配置。


相关文章
SpringBoot 集成log4j2
SpringBoot 集成log4j2
537 0
SpringBoot 集成log4j2
|
JSON 前端开发 Java
SpringBoot项目Http406错误问题解决
一、背景 1、自定义了返回类 2、控制器使用@ResponseBody注解标记
|
2月前
|
存储 JSON 前端开发
使用阿里巴巴FastJson的设置
本文对比了 fastJson 与 jackson 在使用难度、功能支持及性能上的差异,介绍了 fastJson 的依赖引入与 null 值处理配置,并通过封装统一的 JSON 返回结构 `JsonResult`,实现包含数据、状态码和提示信息的标准化响应,提升前后端交互的规范性与可维护性。
|
2月前
|
安全 Java jenkins
Spring Boot 多环境配置与 Profile 实战
Spring Boot通过Profile实现多环境配置,支持dev、test、prod等环境的独立配置。通过application-{profile}.yml分离配置,结合spring.profiles.active动态激活,实现一套代码适配多套环境,提升部署效率与安全性。
|
2月前
|
JSON 前端开发 Java
Spring Boot 返回 JSON 数据及数据封装
本课讲解Spring Boot中JSON处理:通过@RestController返回JSON,利用内置Jackson实现对象、List、Map自动序列化,并自定义配置优雅处理null值,提升前后端交互体验。
|
2月前
|
JSON 前端开发 安全
用自定义注解 + 拦截器实现登录鉴权
通过自定义注解 `@Login` 结合 Spring 拦截器,实现声明式登录校验。无需重复编码,自动拦截未登录请求,提升代码可维护性与安全性,适用于前后端分离架构的权限控制实践。
|
Java 测试技术 数据安全/隐私保护
Spring Boot | 一种优雅的参数校验方案(个人总结)
一种优雅的参数校验方案(个人总结)
1988 1
Spring Boot | 一种优雅的参数校验方案(个人总结)
|
JSON Java API
jackson序列化和反序列化中的注解和扩展点大全【收藏】
jackson序列化和反序列化中的注解和扩展点大全【收藏】
|
Java 数据库连接 Spring
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could
这个错误通常出现在使用Spring Boot进行数据库连接时。错误信息表明Spring Boot未能配置一个DataSource,因为没有指定'url'属性,并且没有发现默认的数据库连接。
6160 0
|
XML Java Maven
Springboot整合与使用log4j2日志框架【详解版】
该文介绍了如何在Spring Boot中切换默认的LogBack日志系统至Log4j2。首先,需要在Maven依赖中排除`spring-boot-starter-logging`并引入`spring-boot-starter-log4j2`。其次,创建`log4j2-spring.xml`配置文件放在`src/main/resources`下,配置包括控制台和文件的日志输出、日志格式和文件切分策略。此外,可通过在不同环境的`application.yml`中指定不同的log4j2配置文件。最后,文章提到通过示例代码解释了日志格式中的各种占位符含义。
2287 0