高性能: 核心解析器和生成器经过深度优化,性能远超许多同类库。
功能丰富: 支持标准JSON、JSONPath查询、泛型处理、日期格式化、自定义序列化/反序列化等。
易用性: API 设计简洁直观,JSON
工具类提供了最常用的 toJSONString
和 parseObject
方法。
安全性: 相比 1.x 版本,2.x 在反序列化安全性方面做了大量改进,减少了反序列化漏洞的风险(但仍需谨慎配置和使用)。
1. 简介
Fastjson2 是阿里巴巴开源的高性能 Java JSON 库,是 Fastjson 1.x 的升级版本。
它提供了将 Java 对象与 JSON 字符串相互转换的功能,具有 极快的解析和生成速度 、丰富的功能 以及 良好的安全性(相较于 1.x 版本有显著改进)。
2. 添加依赖
Maven
<dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.57</version>
</dependency>
Gradle
implementation 'com.alibaba.fastjson2:fastjson2:2.0.57'
3. 基本用法
前置准备
public class User {private String name;private int age;private String email;public User() {}public User(String name, int age, String email) {this.name = name;this.age = age;this.email = email;}// get和set省略
}
Fastjson2 的核心入口通常是 com.alibaba.fastjson2.JSON
、com.alibaba.fastjson2.JSONObject
、com.alibaba.fastjson2.JSONArray
类。
3.1 Java对象转为JSON字符串
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;public class JavaObjectToJsonExample {public static void main(String[] args) throws Exception {// 示例数据User user = new User("张三", 25, "123@qq.com");String jsonStr = JSON.toJSONString(user);// 输出: {"name":"张三","age":25,"email":"123@qq.com"}System.out.println(jsonStr); }
}
3.2 JSON字符串转为Java对象
import com.alibaba.fastjson2.JSON;public class JavaObjectToJsonExample {public static void main(String[] args) throws Exception {String jsonString = "{\"name\":\"李四\",\"age\":30,\"email\":\"lisi@example.com\"}"; // 反序列化为指定java对象类型User user = JSON.parseObject(jsonString, User.class);
System.out.println(user.getName()); // 输出: 李四}
}
3.3 JSON字符串转为JSONObject
在数据结构处于未知的情况,可以将JSON字符串转为JSONObject。
import com.alibaba.fastjson2.JSON;public class JsonStrToJSONObjectExample {public static void main(String[] args) throws Exception {String jsonString = "{\"name\":\"李四\",\"age\":30,\"email\":\"lisi@example.com\"}"; JSONObject jsonObject = JSON.parseObject(jsonString);String name = jsonObject.getString("name");Integer age = jsonObject.getInteger("age");}
}
3.4 JSONObject转为JSON字符串
import com.alibaba.fastjson2.JSON;public class JsonStrToJSONObjectExample {public static void main(String[] args) throws Exception {String jsonString = "{\"name\":\"李四\",\"age\":18,\"email\":\"123@qq.com\"}"; JSONObject jsonObject = new JSONObject;jsonObject.put("name", "李四");jsonObject.put("age", 18);jsonObject.put("email", "123@qq.com");// 输出: {"name":"李四","age":18,"email":"123@qq.com"}System.out.println(jsonObject.toJSONString())}
}
3.5 List集合转为JSON字符串
import com.alibaba.fastjson2.JSON;public class JsonStrToJSONObjectExample {public static void main(String[] args) throws Exception {List<User> array = new ArrayList<>;array.add(new User("张三", 18, "123@qq.com"));array.add(new User("李四", 19, "456@qq.com"));String str = JSONArray.toJSONString(array);// 输出: [{"name":"张三","age":18,"email":"123@qq.com"},{"name":"李四","age":19,"email":"456@qq.com"}]System.out.println(str)}
}
3.6 JSON字符串转为List集合
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;public class JsonStrToJSONObjectExample {public static void main(String[] args) throws Exception {String str = "[{\"name\":\"张三\",\"age\":18,\"email\":\"123@qq.com\"},{\"name\":\"李四\",\"age\":19,\"email\":\"456@qq.com\"}]";// 输出: [{"name":"张三","age":18,"email":"123@qq.com"},{"name":"李四","age":19,"email":"456@qq.com"}]// 方式一List<User> array1 = JSONArray.parseArray(str, User.class);// 方式二List<User> array2 = JSON.parseObject(str, new TypeReference<List<User>>(){});}
}
3.7 数组转为JSON字符串
import com.alibaba.fastjson2.JSON;public class JsonToArrayExample {public static void main(String[] args) throws Exception {// JSON 字符串转为 String[] 数组String jsonStr1 = "[\"苹果\", \"香蕉\", \"橙子\"]";String[] strArray = JSON.parseObject(jsonStr1, String[].class);// JSON 字符串转为复杂对象数组String jsonStr2 = "[{\"name\":\"张三\",\"age\":18,\"email\":\"123@qq.com\"},{\"name\":\"李四\",\"age\":19,\"email\":\"456@qq.com\"}]";User[] userArray = JSON.parseObject(jsonStr2, User[].class);}
}
3.8 JSON字符串转为数组
import com.alibaba.fastjson2.JSON;public class ArrayToJsonExample {public static void main(String[] args) throws Exception {User[] users = {new User("张三", 18, "123@qq.com"),new User("李四", 19, "456@qq.com")};String jsonStr = JSON.toJSONString(users);// 输出: [{"name":"张三","age":18,"email":"123@qq.com"},{"name":"李四","age":19,"email":"456@qq.com"}]System.out.println(jsonStr);}
}
3.9 Map 转 JSON 字符串
import com.alibaba.fastjson2.JSON;public class MapToJsonExample {public static void main(String[] args) throws Exception {Map<String, Object> map = new HashMap<>();map.put("name", "张三");map.put("age", 18);map.put("email", "123@qq.com");String jsonStr = JSON.toJSONString(map);// 输出: {"name":"张三","age":18,"email":"123@qq.com"}System.out.println(jsonStr);}
}
3.10 JSON 字符串转Map
案例一:
import com.alibaba.fastjson2.JSON;
import java.util.Map;public class JsonToMapExample {public static void main(String[] args) throws Exception {String jsonStr = "{\"name\":\"张三\",\"age\":18,\"email\":\"123@qq.com\"}"Map<String, Object> map = JSON.parseObject(jsonStr, Map.class);}
}
案例二:
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import java.util.Map;public class JsonToMapExample {public static void main(String[] args) throws Exception {// JSON 字符串,值是 User 对象String jsonStr = "{\"user1\":{\"name\":\"张三\",\"age\":18,\"email\":\"123@qq.com\"},\"user2\":{\"name\":\"李四\",\"age\":19,\"email\":\"456@qq.com\"}}";// 解析为 Map<String, User>Map<String, User> userMap = JSON.parseObject(jsonStr,new TypeReference<Map<String, User>>(){});}
}
4. @JSONField注解的使用
import com.alibaba.fastjson2.annotation.JSONField;@Data
public class Product {private String id;// 转化为JSON后字段名为 product_name@JSONField(name = "product_name")private String name;// 日期格式化@JSONField(format = "yyyy-MM-dd HH:mm:ss")private LocalDateTime releaseDate;// 序列化时忽略此字段@JSONField(serialize = false)private String internalCode;// 反序列化时忽略此字段@JSONField(deserialize = false)private String temporaryStatus;
}
5. 高级特性 JSONPath
Fastjson2 内置了强大的 JSONPath 支持,用于查询和修改 JSON 数据。
import com.alibaba.fastjson2.JSONPath;String jsonStr = "{\"store\":{\"book\":[{\"title\":\"Book1\",\"price\":10},{\"title\":\"Book2\",\"price\":15}],\"bicycle\":{\"price\":50}}}";// 查询所有书的标题
List<String> titles = JSONPath.of("$.store.book[*].title").extract(jsonStr);
// 输出结果为:[Book1, Book2]
System.out.println(titles);// 查询价格大于12的书
List<Object> expensiveBooks = JSONPath.of("$.store.book[?(@.price > 12)]").extract(jsonStr);
// 输出结果为:[{"title":"Book2","price":15}]
System.out.println(expensiveBooks);// 修改价格,将第一本书价格改为12
JSONPath.set(jsonStr, "$.store.book[0].price", 12);