1、简述
在 Java Web 开发中,JSON 数据解析 是非常常见的需求。Spring Boot 默认使用 Jackson 作为 JSON 序列化和反序列化框架,但在一些场景下,开发者可能更习惯使用 Fastjson(阿里巴巴开源的高性能 JSON 解析库)。
样例代码:https://gitee.com/lhdxhl/springboot-example.git
本文将介绍如何在 Spring Boot 中集成 Fastjson,并给出具体实践样例。
2、实践样例
🔹 性能优秀:Fastjson 在序列化和反序列化速度方面表现突出。
🔹 功能强大:支持 JSONPath、循环引用检测、自动类型转换等功能。
🔹 使用简单:API 设计直观,容易上手。
适合用于 日志解析、大规模 JSON 数据处理、缓存序列化 等场景。
2.1 添加依赖
在 pom.xml
中引入 Fastjson 依赖(推荐使用 1.2.83
及以上版本,修复了部分安全漏洞):
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
⚠️ 注意:
fastjson
已升级为fastjson2
,新项目推荐使用fastjson2
。
2.2 定义实体类
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private String email;
}
2.3 基础用法
JSON 字符串转对象
import com.alibaba.fastjson.JSON;
public class FastjsonDemo {
public static void main(String[] args) {
String jsonStr = "{\"id\":1,\"name\":\"Tom\",\"email\":\"tom@mail.com\"}";
User user = JSON.parseObject(jsonStr, User.class);
System.out.println("解析结果: " + user);
}
}
输出:
解析结果: User(id=1, name=Tom, email=tom@mail.com)
对象转 JSON 字符串
User user = new User();
user.setId(2L);
user.setName("Jerry");
user.setEmail("jerry@mail.com");
String json = JSON.toJSONString(user);
System.out.println("序列化结果: " + json);
输出:
序列化结果: {"email":"jerry@mail.com","id":2,"name":"Jerry"}
JSON 数组解析
String jsonArray = "[{\"id\":1,\"name\":\"Tom\"},{\"id\":2,\"name\":\"Jerry\"}]";
List<User> users = JSON.parseArray(jsonArray, User.class);
System.out.println("解析列表: " + users);
输出:
解析列表: [User(id=1, name=Tom, email=null), User(id=2, name=Jerry, email=null)]
2.4 配置 Fastjson
Spring Boot 默认使用 Jackson,如果希望全局替换为 Fastjson,需要配置 HttpMessageConverters
:
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 创建 FastJsonHttpMessageConverter
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 配置 FastJsonConfig
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat, // 美化格式
SerializerFeature.WriteMapNullValue, // 输出空值
SerializerFeature.WriteDateUseDateFormat // 日期格式化
);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
fastConverter.setFastJsonConfig(fastJsonConfig);
// 替换掉默认的 Jackson
converters.clear();
converters.add(fastConverter);
}
}
2.5 Controller 示例
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private static final List<User> userList = new ArrayList<>();
static {
userList.add(new User(1L, "Tom", "tom@mail.com"));
userList.add(new User(2L, "Jerry", "jerry@mail.com"));
}
@GetMapping
public List<User> getUsers() {
return userList; // 自动转 JSON
}
@PostMapping
public String addUser(@RequestBody User user) {
userList.add(user);
return "添加成功:" + user.getName();
}
}
测试:
# 获取用户列表
curl http://localhost:8080/users
# 添加用户
curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"id":3,"name":"Alice","email":"alice@mail.com"}'
3、应用场景
🔹 高并发、高性能需求的系统:Fastjson 以高性能著称,适合电商平台、大数据系统等需要处理大量 JSON 数据的场景。
🔹 灵活处理复杂 JSON 数据:在需要处理嵌套对象、数组、复杂对象映射等场景时,Fastjson 提供了非常灵活的处理能力。
🔹 自定义序列化需求:通过 @JSONField 注解,可以轻松实现复杂的自定义序列化需求。
Fastjson 在性能上表现出色,特别是在大数据量的序列化/反序列化中,其速度相对 Jackson 和 Gson 更加快速。在一些性能测试中,Fastjson 在对象结构复杂或数组较大时仍能保持较好的处理效率。
4、总结
Fastjson 是一款强大且高效的 JSON 库,特别适用于对性能要求较高的场景。它提供了简洁的 API 以及强大的自定义序列化支持,适合处理复杂的 JSON 数据结构。在电商平台、数据交换接口和高性能系统中,Fastjson 是一个优秀的选择。