高性能: 核心解析器和生成器經過深度優化,性能遠超許多同類庫。
功能豐富: 支持標準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);