JSON 是輕量級數據交換格式,Java 生態主流解析庫有 json-lib、org.json、Gson、Jackson 等。本文聚焦前兩者,展示構建與解析核心 API,並對比差異。
依賴:json-lib.jar + ezmorph.jar + commons-lang/logging/beanutils/collections。
// List
List list = Arrays.asList("first", "second");
JSONArray jsonArray = JSONArray.fromObject(list);
// Map
Map map = new HashMap();
map.put("name", "json");
map.put("bool", true);
map.put("int", 1);
map.put("arr", new String[]{"a","b"});
JSONObject json = JSONObject.fromObject(map);
// Bean
JSONObject jsonObj = JSONObject.fromObject(new JsonBean());
// 數組
boolean[] boolArray = {true, false, true};
JSONArray jsonArray = JSONArray.fromObject(boolArray);
// 字符串
JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");
// Bean 集合
List list = ...;
JSONArray ja = JSONArray.fromObject(list);
public class JsonTest {
public static String buildJson() {
JSONObject jo = new JSONObject();
Map map1 = Map.of("name","Alexia","sex","female","age","23");
Map map2 = Map.of("name","Edward","sex","male","age","24");
List
| 維度 | json-lib | org.json |
|---|---|---|
| 體積/依賴 | 較重,依賴 ezmorph、commons 多組件 | 極輕,零依賴 |
| Bean 轉換 | 直接雙向轉換 JSONObject.fromObject(bean) | 不支持直接 Bean 轉換,需先轉 Map |
| API 風格 | 豐富,支持集合、數組、Map、Bean 直接互轉 | 精簡,核心 JSONObject/JSONArray |
| 適用場景 | 大量 Bean/集合互轉、企業級應用 | 簡單 JSON 構建解析、Android、嵌入式 |
json-lib 功能豐富、Bean 支持完善,適合複雜對象圖序列化;org.json 輕量零依賴,適合簡單場景。根據項目依賴預算、對象複雜度選型。現代項目建議考慮 Gson 或 Jackson,性能更優、API 更現代。