在 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 自动配置。