{
\"code\": 0,
\"message\": \"\",
\"data\": [
{
\"info\": {\"id\": 0, \"name\": \"lina\", \"age\": 10},
\"subclass\": []
},
{
\"info\": {\"id\": 1, \"name\": \"may\", \"age\": 16},
\"subclass\": [
{\"info\": {\"id\": 2, \"name\": \"aa\", \"age\": 13}, \"subclass\": []},
{\"info\": {\"id\": 3, \"name\": \"bb\", \"age\": 12}, \"subclass\": []}
]
}
]
}
特徵:data 為陣列,元素包含 info 物件與 subclass 同結構陣列 → **遞歸樹狀結構**。
// Java (Lombok @Data 簡寫)
@Data
class Response {
int code;
String message;
List<Node> data;
}
@Data
class Node {
Info info;
List<Node> subclass; // 遞歸引用自身
}
@Data
class Info {
int id;
String name;
int age;
}
Gson gson = new GsonBuilder().create();
Response resp = gson.fromJson(jsonString, Response.class);
// 遞歸遍歷樹結構
void printTree(Node node, int depth) {
String indent = \" \".repeat(depth);
System.out.println(indent + node.info.id + \" \" + node.info.name + \" \" + node.info.age);
if (node.subclass != null) {
for (Node child : node.subclass) printTree(child, depth + 1);
}
}
for (Node root : resp.data) printTree(root, 0);
List<Node> subclass 因為泛型資訊在編譯期保留於簽名中(ParameterizedType),無需額外 TypeToken。\"subclass\": [] 會映射為空 ArrayList(非 null),遍歷時安全。user_name),需設定 gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)。TypeAdapter。JsonReader reader = new JsonReader(new StringReader(jsonString));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (\"data\".equals(name)) {
reader.beginArray();
while (reader.hasNext()) parseNode(reader); // 手寫遞歸解析邏輯
reader.endArray();
} else reader.skipValue();
}
reader.endObject();
適用於超大 JSON(>100MB),避免全量載入記憶體。
JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY → 資料類結構與 JSON 不匹配,檢查 List<Node> data vs 物件。StackOverflowError → 改用迭代式遍歷或增加 JVM 棧大小 -Xss4m。TypeAdapter 或使用 @Expose 控制序列化方向。定義遞歸資料類 Node { Info info; List<Node> subclass; },Gson 一行代碼完成全樹反序列化。配合遞歸遍歷即可提取任意層級資料。大型 JSON 可改用 JsonReader 流式解析。