好的,以下是一份系统性、综合性、全面的 FastJSON2 常用工具类详细说明文档,包含表格、详细使用示例和实际开发建议。
✅ FastJSON2 常用工具类详解与实战指南
📌 一、FastJSON2 常用工具类总览表
| 工具类 | 作用 | 核心方法 | 常见用法场景 |
|---|---|---|---|
JSON | 核心序列化/反序列化入口 | toJSONString(), parseObject(), parseArray() | 所有 JSON 转换、API 响应、配置解析 |
JSONObject | 动态 JSON 对象(类似 Map) | get(), put(), getString(), getInteger() | 配置动态读取、日志结构化、API 响应构建 |
JSONArray | 动态 JSON 数组(类似 List) | add(), get(), getJSONObject(), size() | 批量数据处理、列表响应构建 |
JSONB | 二进制 JSON 序列化/反序列化 | toBytes(), parseObject(byte[]) | 高性能缓存、RPC、消息队列 |
JSONPath | JSON 数据路径查询 | read() | 从复杂 JSON 中提取部分数据 |
TypeReference | 泛型类型引用 | <init>() | 解析泛型集合 List<T>, Map<K,V> |
SerializerFeature | 序列化选项 | 枚举值 | 控制输出格式(是否输出 null、是否格式化) |
JSONReader.Feature | 反序列化选项 | 枚举值 | 控制解析行为(忽略大小写、允许注释) |
📌 二、各工具类详细使用示例(含中文注释)
✅ 1. JSON 工具类
import com.alibaba.fastjson2.JSON;
import java.util.List;
// 定义一个简单的 JavaBean
class User {
private Long id;
private String name;
private String email;
public User() {} // 必须有无参构造器
// Getter/Setter (此处省略,实际项目推荐用 Lombok @Data)
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
public class JsonExample {
public static void main(String[] args) {
// --- 1.1 序列化 Java 对象为 JSON 字符串 ---
User user = new User();
user.setId(1L);
user.setName("张三");
user.setEmail("zhangsan@company.com");
// 将 Java 对象序列化为 JSON 字符串
String jsonString = JSON.toJSONString(user);
System.out.println("序列化结果: " + jsonString);
// 输出: {"email":"zhangsan@company.com","id":1,"name":"张三"}
// --- 1.2 反序列化 JSON 字符串为 Java 对象 ---
String jsonInput = "{\"id\":2,\"name\":\"李四\",\"email\":\"lisi@company.com\"}";
User parsedUser = JSON.parseObject(jsonInput, User.class); // 指定目标类,安全
System.out.println("反序列化结果: " + parsedUser.getName()); // 输出: 李四
// --- 1.3 反序列化 JSON 字符串为 Java 对象集合 (使用 TypeReference) ---
String jsonArrayStr = "[{\"id\":3,\"name\":\"王五\",\"email\":\"wangwu@company.com\"},{\"id\":4,\"name\":\"赵六\",\"email\":\"zhaoliu@company.com\"}]";
List<User> userList = JSON.parseArray(jsonArrayStr, User.class);
// List<User> userList = JSON.parseObject(jsonArrayStr, new TypeReference<>() {});
System.out.println("反序列化集合大小: " + userList.size()); // 输出: 2
System.out.println("第一个用户: " + userList.get(0).getName()); // 输出: 王五
}
}
✅ 2. JSONObject 工具类
import com.alibaba.fastjson2.JSONObject;
import java.util.Map;
public class JsonObjectExample {
public static void main(String[] args) {
// --- 2.1 从 JSON 字符串解析为 JSONObject ---
String jsonStr = "{\"code\":200,\"message\":\"success\",\"data\":{\"userId\":1001,\"userName\":\"admin\"}}";
JSONObject response = JSONObject.parseObject(jsonStr);
// 获取基本类型值
int code = response.getIntValue("code"); // getIntValue 自动转换为 int
String message = response.getString("message");
System.out.println("状态码: " + code + ", 消息: " + message);
// 获取嵌套的 JSONObject
JSONObject data = response.getJSONObject("data");
Long userId = data.getLong("userId");
String userName = data.getString("userName");
System.out.println("用户ID: " + userId + ", 用户名: " + userName);
// --- 2.2 动态构建 JSONObject ---
JSONObject config = new JSONObject();
config.put("appName", "InsuranceApp");
config.put("version", "2.1.0");
config.put("debug", true);
// 添加一个 Map 作为值,它会自动转换为 JSONObject
Map<String, Object> database = Map.of("host", "localhost", "port", 5432);
config.put("database", database);
System.out.println("构建的配置 JSON: " + config.toJSONString());
// --- 2.3 安全获取值(避免 NPE) ---
String nonExistentValue = response.getString("nonexistent", "default_value");
System.out.println("不存在的键的默认值: " + nonExistentValue); // 输出: default_value
}
}
✅ 3. JSONArray 工具类
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
public class JsonArrayExample {
public static void main(String[] args) {
// --- 3.1 从 JSON 字符串解析为 JSONArray ---
String jsonArrayStr = "[{\"name\":\"苹果\",\"price\":5.5},{\"name\":\"香蕉\",\"price\":3.2},{\"name\":\"橙子\",\"price\":4.8}]";
JSONArray fruits = JSONArray.parseArray(jsonArrayStr);
// 遍历数组
for (int i = 0; i < fruits.size(); i++) {
JSONObject fruit = fruits.getJSONObject(i); // 获取数组中每个元素为 JSONObject
String name = fruit.getString("name");
Double price = fruit.getDouble("price");
System.out.println("水果: " + name + ", 价格: " + price);
}
// --- 3.2 动态构建 JSONArray ---
JSONArray permissions = new JSONArray();
permissions.add("read"); // 添加字符串
permissions.add("write");
permissions.add(true); // 添加布尔值
permissions.add(123); // 添加数字
System.out.println("权限列表: " + permissions.toJSONString());
// --- 3.3 从 JSONObject 中获取 JSONArray ---
String complexJson = "{\"user\":{\"name\":\"张三\",\"hobbies\":[\"读书\",\"游泳\",\"编程\"]}}";
JSONObject complexObj = JSONObject.parseObject(complexJson);
JSONArray hobbies = complexObj.getJSONObject("user").getJSONArray("hobbies");
System.out.println("爱好列表: " + hobbies);
}
}
✅ 4. JSONB 工具类
import com.alibaba.fastjson2.JSONB;
public class JsonbExample {
public static void main(String[] args) {
User user = new User();
user.setId(100L);
user.setName("JSONB 用户");
user.setEmail("jsonb@fastjson.com");
// --- 4.1 序列化为 JSONB 字节数组 ---
byte[] jsonbBytes = JSONB.toBytes(user);
System.out.println("JSONB 字节数组长度: " + jsonbBytes.length); // 比 JSON 字符串小很多
System.out.println("JSONB 字节数组 (Hex): " + bytesToHex(jsonbBytes));
// --- 4.2 从 JSONB 字节数组反序列化为 Java 对象 ---
User deserializedUser = JSONB.parseObject(jsonbBytes, User.class);
System.out.println("从 JSONB 反序列化结果: " + deserializedUser.getName());
// 输出: 从 JSONB 反序列化结果: JSONB 用户
}
// 辅助方法:将字节数组转为十六进制字符串,便于查看
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
✅ 5. JSONPath 工具类
import com.alibaba.fastjson2.JSONPath;
public class JsonPathExample {
public static void main(String[] args) {
String complexJson = """
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
""";
// --- 5.1 从 JSON 字符串中读取数据 ---
// 获取所有书籍的标题
Object titles = JSONPath.read(complexJson, "$.store.book[*].title");
System.out.println("所有书籍标题: " + titles); // 输出: [Sayings of the Century, Sword of Honour]
// 获取第一本书的价格
Object firstBookPrice = JSONPath.read(complexJson, "$.store.book[0].price");
System.out.println("第一本书价格: " + firstBookPrice); // 输出: 8.95
// 获取自行车的颜色
Object bikeColor = JSONPath.read(complexJson, "$.store.bicycle.color");
System.out.println("自行车颜色: " + bikeColor); // 输出: red
// --- 5.2 从 JSONB 字节数组中读取数据 ---
byte[] jsonbBytes = JSONB.toBytes(complexJson); // 将 JSON 字符串转为 JSONB 字节数组
Object expensiveValue = JSONPath.read(jsonbBytes, "$.expensive"); // 直接从字节数组读取,性能更高
System.out.println("expensive 值: " + expensiveValue); // 输出: 10
}
}
✅ 6. TypeReference 工具类
import com.alibaba.fastjson2.JSON;
import java.util.List;
import java.util.Map;
public class TypeReferenceExample {
public static void main(String[] args) {
// --- 6.1 解析泛型 List ---
String listJson = "[{\"name\":\"产品A\",\"price\":100},{\"name\":\"产品B\",\"price\":200}]";
List<Product> productList = JSON.parseObject(listJson, new com.alibaba.fastjson2.TypeReference<List<Product>>() {});
System.out.println("产品列表大小: " + productList.size());
// --- 6.2 解析泛型 Map ---
String mapJson = "{\"key1\":{\"name\":\"商品1\"},\"key2\":{\"name\":\"商品2\"}}";
Map<String, Product> productMap = JSON.parseObject(mapJson, new com.alibaba.fastjson2.TypeReference<Map<String, Product>>() {});
System.out.println("Map 中 key1 对应的商品名: " + productMap.get("key1").getName());
// --- 6.3 解析复杂嵌套泛型 ---
String nestedJson = "[{\"groupId\":\"G1\",\"items\":[{\"name\":\"Item1\"},{\"name\":\"Item2\"}]}]";
List<Group> groups = JSON.parseObject(nestedJson, new com.alibaba.fastjson2.TypeReference<List<Group>>() {});
System.out.println("分组数量: " + groups.size());
}
// 辅助类
static class Product {
private String name;
private Double price;
// getter/setter (省略)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
}
static class Group {
private String groupId;
private List<Product> items;
// getter/setter (省略)
public String getGroupId() { return groupId; }
public void setGroupId(String groupId) { this.groupId = groupId; }
public List<Product> getItems() { return items; }
public void setItems(List<Product> items) { this.items = items; }
}
}
✅ 7. SerializerFeature 工具类
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.config.JSONWriter;
public class SerializerFeatureExample {
public static void main(String[] args) {
User user = new User();
user.setId(1L);
user.setName("张三");
// user.setEmail(null); // 假设 email 为 null
// --- 7.1 默认序列化(忽略 null 字段) ---
String defaultJson = JSON.toJSONString(user);
System.out.println("默认序列化: " + defaultJson); // 输出: {"id":1,"name":"张三"}
// --- 7.2 序列化时输出 null 字段 ---
String withNullJson = JSON.toJSONString(user, JSONWriter.Feature.WriteMapNullValue);
System.out.println("输出 null 字段: " + withNullJson); // 输出: {"email":null,"id":1,"name":"张三"}
// --- 7.3 格式化输出(美化) ---
String prettyJson = JSON.toJSONString(user, JSONWriter.Feature.PrettyFormat);
System.out.println("格式化输出:\n" + prettyJson);
/*
输出:
{
"id": 1,
"name": "张三"
}
*/
// --- 7.4 组合多个 Feature ---
String combinedJson = JSON.toJSONString(user,
JSONWriter.Feature.WriteMapNullValue, // 输出 null
JSONWriter.Feature.PrettyFormat // 格式化
);
System.out.println("组合 Feature 输出:\n" + combinedJson);
}
}
✅ 8. JSONReader.Feature 工具类
import com.alibaba.fastjson2.JSON;
public class JsonReaderFeatureExample {
public static void main(String[] args) {
// JSON 字段名与 JavaBean 不完全匹配(大小写不一致)
String jsonWithWrongCase = "{\"Name\":\"李四\",\"AGE\":30,\"Email\":\"lisi@company.com\"}";
// --- 8.1 默认反序列化(严格匹配,会失败) ---
try {
User user = JSON.parseObject(jsonWithWrongCase, User.class);
System.out.println("默认反序列化结果: " + user.getName()); // 可能为 null
} catch (Exception e) {
System.out.println("默认反序列化失败或字段映射失败");
}
// --- 8.2 使用 Feature 忽略字段名大小写 ---
User userIgnoreCase = JSON.parseObject(jsonWithWrongCase, User.class,
com.alibaba.fastjson2.config.JSONReader.Feature.IgnoreCase);
System.out.println("忽略大小写反序列化结果: " + userIgnoreCase.getName()); // 输出: 李四
System.out.println("年龄: " + userIgnoreCase.getAge()); // 输出: 30
}
}
📌 三、实际开发使用建议
| 类别 | 建议 | 说明 |
|---|---|---|
| 核心使用 | 优先使用 JSON.toJSONString() 和 JSON.parseObject(json, Class.class) | 简洁、安全、性能好 |
| 泛型处理 | 使用 TypeReference 解析 List<T>, Map<K,V> | 避免泛型擦除导致类型错误 |
| 性能优化 | 高并发、低延迟场景(如缓存、RPC)使用 JSONB | 比 JSON 字符串序列化快 3~5 倍,体积小 40% |
| 数据提取 | 从复杂 JSON 中只取部分字段 → 使用 JSONPath.read() | 避免反序列化整个对象,节省 CPU 和内存 |
| 安全防护 | 严禁使用 JSON.parse(String) 解析不可信输入 | 该方法可能引发反序列化漏洞,始终使用 parseObject(json, TargetClass.class) |
| 空值处理 | 在 Spring Boot 配置中全局设置 WriteMapNullValue 等 Feature | 统一处理 null 值,避免前端报错 |
| 日期格式 | 使用 @JSONField(format="yyyy-MM-dd HH:mm:ss") 注解 | 避免默认时间戳格式,提升可读性 |
| Spring Boot 集成 | 显式配置 FastJSON2 作为默认 JSON 序列化器 | 避免 Jackson 与 FastJSON2 冲突,确保性能 |
| 日志打印 | 调试时使用 toJSONString(obj, PrettyFormat) | 便于阅读,但生产环境应关闭,避免性能损耗 |
| 版本管理 | 始终使用最新稳定版 | 修复了历史安全漏洞,性能持续优化 |
| 团队规范 | 在团队代码规范中强制要求使用 parseObject(json, Class.class) | 从源头杜绝安全风险 |
✅ 总结
FastJSON2 提供了功能强大且灵活的工具类,涵盖了从基本的序列化/反序列化到高性能的二进制格式和路径查询。在实际开发中,应根据具体场景选择合适的工具和方法,特别是在性能敏感和安全要求高的项目(如银行、保险系统)中,合理运用 JSONB 和 JSONPath 能显著提升系统效率和安全性。


被折叠的 条评论
为什么被折叠?



