JSON 已成為現代應用數據交換的事實標準。Java 生態系提供多種成熟庫處理 JSON 序列化與反序列化,本文針對 org.json、json-lib (net.sf.json)、Jackson/Gson(補充) 三大主流方案進行實戰演示,幫助開發者快速選型並避坑。
特點:零依賴、API 簡潔、適合簡單場景,但功能較弱(不支援泛型反序列化、日期格式化等)。
public class OrgJsonDemo {
public static void main(String[] args) throws JSONException {
JSONObject json = new JSONObject("{\"name\":\"reiz\"}");
json.put("initial", json.getString("name").substring(0, 1).toUpperCase());
String[] likes = {"JavaScript", "Skiing", "Apple Pie"};
json.put("likes", likes);
Map<String, String> ingredients = new HashMap<>();
ingredients.put("apples", "3kg");
ingredients.put("sugar", "1kg");
json.put("ingredients", ingredients);
System.out.println(json.toString(2)); // 格式化輸出
}
}
輸出:
{
"name": "reiz",
"initial": "R",
"likes": ["JavaScript", "Skiing", "Apple Pie"],
"ingredients": {"apples": "3kg", "sugar": "1kg"}
}
依賴:json-lib、ezmorph、commons-lang、commons-beanutils、commons-collections、commons-logging。適合舊專案維護,新專案建議改用 Jackson/Gson。
public class JsonLibListDemo {
public static void main(String[] args) {
// 1. 基本型別陣列
boolean[] boolArr = {true, false, true};
System.out.println(JSONArray.fromObject(boolArr)); // [true,false,true]
// 2. List 集合
List<String> list = Arrays.asList("first", "second");
System.out.println(JSONArray.fromObject(list)); // ["first","second"]
// 3. JSON 字串
System.out.println(JSONArray.fromObject("['json','is','easy']")); // ["json","is","easy"]
}
}
public class JsonLibParseDemo {
public static void main(String[] args) {
// List
String listStr = "[\"apple\",\"orange\"]";
Collection<String> fruits = JSONArray.toCollection(
JSONArray.fromObject(listStr), String.class);
fruits.forEach(System.out::println);
// Map (含巢狀結構)
String mapStr = "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}";
Map<String, Object> map = (Map) JSONObject.toBean(
JSONObject.fromObject(mapStr), Map.class);
map.forEach((k, v) -> System.out.println(k + " = " + v));
}
}
| 特性 | Jackson | Gson |
|---|---|---|
| 效能 | 極高(流式 API) | 高 |
| 泛型支援 | 完善 | 需 TypeToken |
| 日期/枚舉/Null 處理 | 豐富註解 | 靈活配置 |
| Spring Boot 整合 | 預設內建 | 需額外引入 |
ObjectMapper mapper = new ObjectMapper();
// 序列化
String json = mapper.writeValueAsString(userList);
// 反序列化
List<User> users = mapper.readValue(json, new TypeReference<List<User>>(){});
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
// 序列化
String json = gson.toJson(userList);
// 反序列化
Type type = new TypeToken<List<User>>(){}.getType();
List<User> users = gson.fromJson(json, type);