Fastjson2 全面使用指南(Java后端开发者版)
一、基础使用
1. Parse JSON into JSONObject
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
public class JSONObjectExample {
public static void main(String[] args) {
// 定义JSON字符串
String jsonStr = "{\"name\":\"张三\", \"age\": 30, \"isStudent\": false}";
// 将JSON字符串解析为JSONObject对象
JSONObject jsonObject = JSON.parseObject(jsonStr); // 直接解析为JSONObject类型
// 获取字段值
String name = jsonObject.getString("name"); // 返回"张三"
int age = jsonObject.getInteger("age"); // 返回30
boolean isStudent = jsonObject.getBoolean("isStudent"); // 返回false
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
System.out.println("是否学生: " + isStudent);
}
}
2. Parse JSON into JSONArray
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
public class JSONArrayExample {
public static void main(String[] args) {
// 定义JSON数组字符串
String jsonArrayStr = "[{\"name\":\"张三\",\"age\":30}, {\"name\":\"李四\",\"age\":25}]";
// 将JSON字符串解析为JSONArray对象
JSONArray jsonArray = JSON.parseArray(jsonArrayStr); // 直接解析为JSONArray类型
// 遍历数组
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject item = jsonArray.getJSONObject(i); // 获取每个JSON对象
String name = item.getString("name");
int age = item.getInteger("age");
System.out.println("第" + (i+1) + "个用户: " + name + ", 年龄: " + age);
}
}
}
3. Parse JSON into a Java Object
import com.alibaba.fastjson2.JSON;
class Student {
private String name;
private int age;
private boolean isStudent;
// getter/setter方法(Lombok可简化)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public boolean isStudent() { return isStudent; }
public void setStudent(boolean student) { isStudent = student; }
}
public class JavaObjectParseExample {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"王五\", \"age\": 22, \"isStudent\": true}";
// 将JSON字符串解析为Student对象
Student student = JSON.parseObject(jsonStr, Student.class); // 指定目标类类型
System.out.println("学生姓名: " + student.getName());
System.out.println("年龄: " + student.getAge());
System.out.println("是否学生: " + student.isStudent());
}
}
4. Serialization Java Object to JSON
import com.alibaba.fastjson2.JSON;
public class ObjectToJsonExample {
public static void main(String[] args) {
Student student = new Student();
student.setName("赵六");
student.setAge(24);
student.setStudent(true);
// 将Java对象序列化为JSON字符串
String jsonStr = JSON.toJSONString(student); // 默认格式化输出
System.out.println("序列化后的JSON: " + jsonStr);
// 输出: {"name":"赵六","age":24,"isStudent":true}
}
}
5. Use JSONObject, JSONArray
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
public class JSONObjectArrayUsage {
public static void main(String[] args) {
// 创建JSONObject
JSONObject user = new JSONObject();
user.put("name", "张三");
user.put("age", 30);
user.put("address", new JSONObject().put("city", "北京").put("street", "中关村"));
// 创建JSONArray
JSONArray hobbies = new JSONArray();
hobbies.add("篮球");
hobbies.add("编程");
hobbies.add("旅行");
// 添加到JSONObject
user.put("hobbies", hobbies);
// 转换为JSON字符串
String jsonString = user.toJSONString(); // 转换为标准JSON字符串
System.out.println("构建的JSON: " + jsonString);
// 输出: {"name":"张三","age":30,"address":{"city":"北京","street":"中关村"},"hobbies":["篮球","编程","旅行"]}
}
}
6. Serialize JavaBean to JSON
import com.alibaba.fastjson2.JSON;
class Employee {
private String name;
private int id;
private double salary;
// getter/setter
}
public class JavaBeanToJsonExample {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("李四");
emp.setId(1001);
emp.setSalary(15000.5);
// 序列化JavaBean为JSON
String json = JSON.toJSONString(emp);
// 配置序列化选项(例如不输出null值)
String jsonWithoutNull = JSON.toJSONString(emp,
JSONWriter.Feature.WriteNulls, // 不输出null字段
JSONWriter.Feature.PrettyFormat // 格式化输出
);
System.out.println("默认序列化: " + json);
System.out.println("优化后序列化: " + jsonWithoutNull);
}
}
二、高级使用
1. Serialize JavaBean to JSONB
import com.alibaba.fastjson2.JSONB;
public class JSONBSerializationExample {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("王五");
emp.setId(1002);
emp.setSalary(20000.0);
// 将JavaBean序列化为JSONB二进制格式
byte[] jsonbBytes = JSONB.toBytes(emp); // 二进制格式,体积更小性能更高
System.out.println("JSONB二进制数据长度: " + jsonbBytes.length);
// 输出: JSONB二进制数据长度: 28(具体长度取决于数据)
}
}
2. Parse JSONB to JavaBean
import com.alibaba.fastjson2.JSONB;
public class JSONBDeserializationExample {
public static void main(String[] args) {
// 假设已有JSONB二进制数据
byte[] jsonbBytes = { /* ... */ };
// 将JSONB二进制数据反序列化为Employee对象
Employee emp = JSONB.parseObject(jsonbBytes, Employee.class); // 支持JSONB协议的反序列化
System.out.println("反序列化后的员工姓名: " + emp.getName());
System.out.println("ID: " + emp.getId());
System.out.println("薪资: " + emp.getSalary());
}
}
3. Use JSONPath to read partial data
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPath;
public class JSONPathExample {
public static void main(String[] args) {
String json = "{\"user\":{\"name\":\"张三\",\"age\":30,\"address\":{\"city\":\"北京\",\"street\":\"中关村\"}}}";
// 使用JSONPath提取特定字段
String name = JSONPath.read(json, "$.user.name").toString(); // 返回"张三"
int age = JSONPath.read(json, "$.user.age"); // 返回30
String city = JSONPath.read(json, "$.user.address.city").toString(); // 返回"北京"
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
System.out.println("城市: " + city);
// 提取数组中的元素
String arrayJson = "[{\"id\":1,\"name\":\"A\"}, {\"id\":2,\"name\":\"B\"}]";
String secondName = JSONPath.read(arrayJson, "$[1].name").toString(); // 返回"B"
System.out.println("数组第二个元素的name: " + secondName);
}
}
4. Read part of byte[] data using JSONPath
import com.alibaba.fastjson2.JSONB;
import com.alibaba.fastjson2.JSONPath;
public class JSONPathByteExample {
public static void main(String[] args) {
// 创建JSONB二进制数据
Employee emp = new Employee();
emp.setName("李四");
emp.setId(1003);
emp.setSalary(18000.0);
byte[] jsonbBytes = JSONB.toBytes(emp);
// 使用JSONPath从二进制数据中读取特定字段
String name = JSONPath.read(jsonbBytes, "$.name").toString(); // 直接从byte[]中读取
double salary = JSONPath.read(jsonbBytes, "$.salary"); // 返回18000.0
System.out.println("姓名: " + name);
System.out.println("薪资: " + salary);
}
}
5. 高级JSONPath应用场景
import com.alibaba.fastjson2.JSONPath;
public class AdvancedJSONPath {
public static void main(String[] args) {
String json = "{\"employees\":[{\"name\":\"张三\",\"age\":30},{\"name\":\"李四\",\"age\":25}]}";
// 复杂路径查询
Object names = JSONPath.read(json, "$.employees[*].name"); // 返回["张三","李四"]的List
Object ages = JSONPath.read(json, "$.employees[?(@.age>28)].name"); // 返回["张三"]
System.out.println("所有员工姓名: " + names);
System.out.println("年龄大于28的员工: " + ages);
// 多字段查询
Object result = JSONPath.read(json, "$.employees[?(@.age>25)].{name,age}");
System.out.println("多字段查询结果: " + result);
}
}
三、使用建议与最佳实践
1. 性能优化建议
- 大数据量场景:使用
BeanToArray特性减少JSON体积,可提升20%以上序列化性能 - 二进制格式:在内部系统通信中优先使用JSONB格式,比JSON字符串节省30%~50%空间
- 避免默认序列化:使用
JSONWriter.Feature自定义序列化选项,例如:String json = JSON.toJSONString(obj, JSONWriter.Feature.WriteNulls, // 保留null字段 JSONWriter.Feature.PrettyFormat, // 格式化输出 JSONWriter.Feature.WriteClassName // 保留类名信息 );
2. 泛型处理规范
- 非泛型对象:直接使用
JSON.parseObject(json, Class.class) - 泛型集合:必须使用
TypeReference处理,例如:Type listType = new TypeReference<List<Employee>>(){}.getType(); List<Employee> list = JSON.parseObject(jsonStr, listType);
3. 安全使用规范
- JSONPath注入防护:对不可信的JSONPath表达式进行白名单过滤
- 反序列化安全:使用
JSONReader.Feature.SupportAutoType时需谨慎,建议设置白名单 - 敏感字段处理:使用
@JSONField(serialize = false)注解排除敏感字段
4. 特性配置推荐
// 全局配置示例(适用于Spring Boot)
@Bean
public JSONFactory jsonFactory() {
return new JSONFactory()
.setFeature(JSONWriter.Feature.WriteNulls, false) // 不输出null字段
.setFeature(JSONWriter.Feature.MapSortField, true) // 保持字段顺序
.setFeature(JSONWriter.Feature.BeanToArray, true); // 大数据量场景优化
}
5. 版本选择建议
- 生产环境:使用最新稳定版(当前为2.0.45+)
- 兼容性考虑:若需兼容旧版Fastjson,注意
JSON.parseObject与JSON.parse的区别 - Spring Boot集成:通过
@EnableAutoConfiguration(exclude = FastjsonAutoConfiguration.class)排除默认配置
重要提示:所有序列化/反序列化操作应始终指定目标类型,避免使用
Object类型接收,防止潜在的安全风险。对于复杂对象图,建议使用JSONB格式并启用WriteClassName特性确保类型安全
5万+

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



