Java是一種廣泛應(yīng)用于各個(gè)領(lǐng)域的編程語言,而List和Tree是Java中常用的數(shù)據(jù)結(jié)構(gòu)。在實(shí)際開發(fā)中,我們有時(shí)需要將List數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)為樹形結(jié)構(gòu),并將其轉(zhuǎn)為JSON格式輸出。
下面我們來看一個(gè)示例:
public static ListmockDepartments() { List departments = new ArrayList<>(); Department dep1 = new Department(1, "總部", 0); Department dep2 = new Department(2, "技術(shù)部", 1); Department dep3 = new Department(3, "開發(fā)組", 2); Department dep4 = new Department(4, "測(cè)試組", 2); Department dep5 = new Department(5, "運(yùn)營部", 1); Department dep6 = new Department(6, "市場(chǎng)部", 1); Department dep7 = new Department(7, "銷售部", 6); departments.add(dep1); departments.add(dep2); departments.add(dep3); departments.add(dep4); departments.add(dep5); departments.add(dep6); departments.add(dep7); return departments; }
這段代碼創(chuàng)建了一個(gè)Department對(duì)象的List。我們需要將List轉(zhuǎn)為樹形結(jié)構(gòu),并將其轉(zhuǎn)為JSON格式輸出。
public static JsonNode listToTree(Listlist, int rootId) { ObjectNode rootNode = JsonNodeFactory.instance.objectNode(); // 遞歸構(gòu)造樹 buildTree(rootNode, list, rootId); return rootNode.get("children"); } public static void buildTree(JsonNode parentNode, List list, int parentId) { ArrayNode childrenNode = JsonNodeFactory.instance.arrayNode(); for (Department department : list) { if (department.getParentId() == parentId) { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("id", department.getId()); node.put("name", department.getName()); // 遞歸構(gòu)造子樹 buildTree(node, list, department.getId()); childrenNode.add(node); } } // 將子節(jié)點(diǎn)添加到父節(jié)點(diǎn) if (childrenNode.size() >0) { ((ObjectNode) parentNode).put("children", childrenNode); } }
該示例使用了Jackson庫構(gòu)造JSON。代碼首先創(chuàng)建了一個(gè)ObjectNode作為根節(jié)點(diǎn),然后調(diào)用buildTree()方法遞歸構(gòu)造整棵樹。在buildTree()方法中,首先創(chuàng)建一個(gè)ArrayNode作為子節(jié)點(diǎn)容器,然后遍歷List,找到該節(jié)點(diǎn)的所有子節(jié)點(diǎn)并添加到子節(jié)點(diǎn)容器中。遞歸構(gòu)造子樹后,將子節(jié)點(diǎn)容器添加到父節(jié)點(diǎn)中,并返回子節(jié)點(diǎn)容器。
最后我們將listToTree()方法返回的JsonNode對(duì)象的children字段讀取出來,即可得到完整的樹形JSON。