使用阿里巴巴 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
551 0
SpringBoot 集成log4j2
|
3月前
|
JSON 前端开发 Java
Spring Boot 返回 JSON 数据及数据封装
本课讲解Spring Boot中JSON处理:通过@RestController返回JSON,利用内置Jackson实现对象、List、Map自动序列化,并自定义配置优雅处理null值,提升前后端交互体验。
|
JSON 前端开发 Java
SpringBoot项目Http406错误问题解决
一、背景 1、自定义了返回类 2、控制器使用@ResponseBody注解标记
|
3月前
|
存储 JSON 前端开发
使用阿里巴巴FastJson的设置
本文对比了 fastJson 与 jackson 在使用难度、功能支持及性能上的差异,介绍了 fastJson 的依赖引入与 null 值处理配置,并通过封装统一的 JSON 返回结构 `JsonResult`,实现包含数据、状态码和提示信息的标准化响应,提升前后端交互的规范性与可维护性。
|
SQL XML 关系型数据库
Mybatis-Plus通过SQL注入器实现真正的批量插入
Mybatis-Plus通过SQL注入器实现真正的批量插入
7809 0
Mybatis-Plus通过SQL注入器实现真正的批量插入
|
3月前
|
JSON 前端开发 Java
Spring Boot 封装统一返回的数据结构
本课讲解如何设计统一的JSON响应结构,通过泛型类`JsonResult&lt;T&gt;`封装返回数据,规范包含code、msg、data的标准格式,提升前后端协作效率与API可维护性。
|
3月前
|
安全 Java jenkins
Spring Boot 多环境配置与 Profile 实战
Spring Boot通过Profile实现多环境配置,支持dev、test、prod等环境的独立配置。通过application-{profile}.yml分离配置,结合spring.profiles.active动态激活,实现一套代码适配多套环境,提升部署效率与安全性。
|
11月前
|
JSON 前端开发 Java
深入理解 Spring Boot 中日期时间格式化:@DateTimeFormat 与 @JsonFormat 完整实践
在 Spring Boot 开发中,日期时间格式化是前后端交互的常见痛点。本文详细解析了 **@DateTimeFormat** 和 **@JsonFormat** 两个注解的用法,分别用于将前端传入的字符串解析为 Java 时间对象,以及将时间对象序列化为指定格式返回给前端。通过完整示例代码,展示了从数据接收、业务处理到结果返回的全流程,并总结了解决时区问题和全局配置的最佳实践,助你高效处理日期时间需求。
1555 0
|
Java 测试技术 数据安全/隐私保护
Spring Boot | 一种优雅的参数校验方案(个人总结)
一种优雅的参数校验方案(个人总结)
2030 1
Spring Boot | 一种优雅的参数校验方案(个人总结)
|
SQL Java 数据库连接
自定义HikariCP连接池
自定义HikariCP连接池
1822 0

热门文章

最新文章