Spring Boot 集成 Fastjson2 完整教程:从入门到避坑

Fastjson2 是阿里推出的高性能、安全、全场景支持 的 JSON 处理库,相比 1.x 更快、更安全、Bug 更少,支持 JSONB、JSONPath、Kotlin、GraalVM 等特性。这篇文章带你在 Spring Boot 项目里快速集成、正确配置、避开常见坑。


一、Fastjson2 核心优势

  • 性能远超 Fastjson1.x、Jackson、Gson
  • 修复大量历史安全漏洞
  • 支持 JSON/JSONB 双格式
  • JSONPath 原生支持
  • 兼容 Java/Android/Kotlin/大数据/GraalVM
  • Spring MVC 无缝集成

二、Spring Boot 集成步骤

1. Maven 依赖(直接复制)

复制代码
<!-- fastjson2 核心 -->
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.40</version>
</dependency>

<!-- Spring5/SpringBoot2 扩展包 -->
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2-extension-spring5</artifactId>
    <version>2.0.40</version>
</dependency>

2. 替换 Spring MVC 消息转换器

把 Spring 默认的 Jackson 换成 Fastjson2,让 @ResponseBody / @RequestBody 都走 Fastjson2。

复制代码
@Configuration
public class Fastjson2Config implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        // Fastjson 配置
        FastJsonConfig config = new FastJsonConfig();
        // 日期格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        // 序列化特性:输出null、格式化、BigDecimal不丢精度
        config.setWriterFeatures(
                JSONWriter.Feature.WriteMapNullValue,
                JSONWriter.Feature.PrettyFormat,
                JSONWriter.Feature.WriteBigDecimalAsPlain
        );
        // 反序列化特性:支持数组转Bean、字段匹配更智能
        config.setReaderFeatures(
                JSONReader.Feature.FieldBased,
                JSONReader.Feature.SupportArrayToBean,
                JSONReader.Feature.SupportSmartMatch
        );

        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

        // 放到最前面优先使用
        converters.add(0, converter);
    }
}

3. 测试接口

复制代码
@RestController
public class TestController {

    @GetMapping("/test")
    public Map<String, Object> test() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "Fastjson2 集成成功");
        map.put("nullValue", null);
        return map;
    }
}

启动访问:http://localhost:8080/test

返回格式化 JSON、null 正常输出 → 集成成功。


三、Fastjson2 常用 API

1. Java 对象 → JSON 字符串

复制代码
String json = JSON.toJSONString(obj);

2. JSON 字符串 → Java 对象

复制代码
User user = JSON.parseObject(json, User.class);

3. JSON 数组 → List

复制代码
List<User> userList = JSON.parseArray(json, User.class);

4. List → JSON 字符串

复制代码
String json = JSON.toJSONString(list);

5. JSONPath 读取(超好用)

复制代码
String name = JSONPath.of(json).getString("$.data.name");

四、生产必看:2 个高频坑 + 解决方案

坑1:BigDecimal 精度丢失(非常重要)

问题 :-40090.07 变成 -40090.7,金额直接出错。

原因:默认以科学计数/浮点处理。

解决 :加特性 WriteBigDecimalAsPlain

复制代码
JSON.toJSONString(obj, JSONWriter.Feature.WriteBigDecimalAsPlain);

坑2:日期解析/格式化异常

问题 :yyyy-MM-dd HH:mm:ss 格式无法解析。

解决:

  1. 全局配置日期格式

  2. 字段上加注解

    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;


五、推荐配置(生产直接用)

复制代码
// 序列化推荐
config.setWriterFeatures(
    JSONWriter.Feature.WriteMapNullValue,        // 输出 null 字段
    JSONWriter.Feature.WriteBigDecimalAsPlain,   // BigDecimal 不丢精度
    JSONWriter.Feature.PrettyFormat,             // 格式化输出
    JSONWriter.Feature.WriteDateUseDateFormat    // 全局日期格式化
);

// 反序列化推荐
config.setReaderFeatures(
    JSONReader.Feature.SupportSmartMatch,        // 智能匹配字段
    JSONReader.Feature.IgnoreNullCheck,          // 忽略 null 检查
    JSONReader.Feature.AllowUnmatchedField      // 忽略不存在字段
);

六、总结

  • Fastjson2 = 高性能 + 安全 + 功能强
  • Spring Boot 集成只需两步:引依赖 + 配置转换器
  • 生产务必开启:WriteBigDecimalAsPlain 防止金额精度丢失
  • 日期全局配置 + 注解双保险
相关推荐
小科先生42 分钟前
Java springboot调用数据库的基本流程
java·数据库·spring boot
QXWZ_IA2 小时前
测绘单位采购RTK:设备价格、账号年费、售后,用时间轴分权重
网络·人工智能·安全
IT大白鼠4 小时前
GitLab 未认证 RCE 应急实战CVE-2026-97229(CVSS 10.0)
网络·安全·gitlab
进击的荆棘4 小时前
Linux系统——线程同步与互斥之线程池和安全
linux·运维·服务器·安全·单例模式·线程
KCENN4 小时前
安全地毯压敏传感防护在工业流水线与机器人作业区的耐腐蚀材质及紧急停机机制
安全
北城笑笑5 小时前
Vue 109 ,从零搭建 Vue3 + Electron 工程:生态、安全桥接与打包选型( Vue + Electron )
前端·javascript·vue.js·安全·electron·vue
杨凯凡7 小时前
Spring Boot 链路追踪实战:Micrometer、TraceId 与异步线程上下文传播
java·spring boot·后端
计算机毕设定制辅导-无忧学长7 小时前
《基于Spring Boot的迷游哈游戏综合服务平台的开发》
java·vue.js·spring boot·mysql·迷游哈游戏综合服务平台
山东科恩光电17 小时前
安全触边在协作机器人工作站防碰撞防护中的安装方案与性能优化
安全
梦想恒远21 小时前
Spring Boot + LangChain4j 统计 token 成本:ChatModelListener 实测与单价口径
spring boot·后端