JSON-lib 依賴以下 JAR(Maven 坐標):
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- 傳遞依賴通常會自動引入:commons-lang, commons-beanutils, commons-collections, commons-logging, ezmorph -->
JSONObject:對應 JSON 物件 {...},鍵值對集合。JSONArray:對應 JSON 陣列 [...],有序值列表。JSON 介面,支援 put()、get()、toString()、fromObject() 等。import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonBasicDemo {
public static void main(String[] args) {
// 1. 構建 JSONObject
JSONObject user = new JSONObject();
user.put("username", "huangwuyi");
user.put("sex", "男");
user.put("qq", "413425430");
user.put("minScore", 99);
user.put("nickname", "夢中間境");
// 2. 追加屬性
user.element("address", "福建省廈門市"); // element() 相當於 put()
// 3. 嵌套 JSONArray
JSONArray tags = new JSONArray();
tags.add("Java");
tags.add("JSON");
tags.add("Tutorial");
user.element("tags", tags);
// 4. 輸出完整 JSON 字符串
System.out.println(user.toString());
// {"username":"huangwuyi","sex":"男","qq":"413425430","minScore":99,"nickname":"夢中間境","address":"福建省廈門市","tags":["Java","JSON","Tutorial"]}
// 5. 讀取值
String username = user.getString("username");
int score = user.getInt("minScore");
JSONArray arr = user.getJSONArray("tags");
System.out.println("第一個標籤:" + arr.getString(0));
}
}
public class JsonNestingDemo {
public static void main(String[] args) {
// 1. 物件嵌套物件
JSONObject addr = new JSONObject();
addr.put("city", "廈門");
addr.put("street", "軟件園二期");
JSONObject person = new JSONObject();
person.put("name", "張三");
person.put("address", addr); // 直接放 JSONObject
System.out.println("嵌套物件:" + person);
// {"name":"張三","address":{"city":"廈門","street":"軟件園二期"}}
// 2. 陣列嵌套物件
JSONArray list = new JSONArray();
list.add(person);
list.add(new JSONObject().put("name", "李四"));
JSONObject wrapper = new JSONObject();
wrapper.put("users", list);
System.out.println("陣列嵌套:" + wrapper);
// {"users":[{"name":"張三","address":{...}},{"name":"李四"}]}
// 3. 字符串反序列化回對象
String jsonStr = wrapper.toString();
JSONObject parsed = JSONObject.fromObject(jsonStr);
System.out.println("反序列化取名:" + parsed.getJSONArray("users").getJSONObject(0).getString("name"));
}
}
JSONObject obj = new JSONObject();
System.out.println("是否陣列:" + obj.isArray()); // false
System.out.println("是否空:" + obj.isEmpty()); // true
System.out.println("是否NullObject:" + obj.isNullObject()); // false
// 依賴 json-lib 的 Bean 處理能力
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class BeanJsonDemo {
static class User {
private String name;
private int age;
// getter/setter 省略
@Override public String toString() { return "User{name='" + name + "', age=" + age + '}'; }
}
public static void main(String[] args) {
// Bean → JSON
User u = new User();
u.setName("Alice");
u.setAge(25);
JSONObject json = JSONObject.fromObject(u);
System.out.println("Bean to JSON: " + json); // {"name":"Alice","age":25}
// JSON → Bean (需 JsonConfig 指定類型)
JsonConfig config = new JsonConfig();
config.setRootClass(User.class);
User u2 = (User) JSONObject.toBean(json, config);
System.out.println("JSON to Bean: " + u2);
}
}
JsonConfig 可註冊 JsonValueProcessor 處理 Date 序列化。JsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT) 避免棧溢出。JSON-lib 曾是 Java JSON 處理的主流選擇,理解其 JSONObject/JSONArray 核心操作有助於維護舊專案。新專案請優先選擇 Jackson/Gson/Fastjson2。