/** * * @param rootList 根結點 * @param listAll 全部結點 * @param parentId 父子組織關係依賴屬性 * @return 返回樹形字符串 */ public String getTree(List<?> rootList, List<?> listAll, String parentId) { JSONArray jsonRootList = JSONArray.fromObject(rootList); JSONArray jsonListAll = JSONArray.fromObject(listAll); // 初始化根節點的等級 for (int i = 0; i < jsonRootList.size(); i++) { jsonRootList.getJSONObject(i).put("treeLevel", 1); } getTreeChildren(jsonRootList, jsonListAll, parentId); return jsonRootList.toString(); } /*********** * 遞歸獲取子節點 * * @param tree * @param listAll */ //@Override private void getTreeChildren(JSONArray tree, JSONArray listAll, String parentId) { for (int i = 0; i < tree.size(); i++) { JSONObject node = tree.getJSONObject(i); JSONArray children = new JSONArray(); for (int j = 0; j < listAll.size(); j++) { JSONObject jsonObject = listAll.getJSONObject(j); if (jsonObject.getInt(parentId) == node.getInt("id")) {//是子節點 jsonObject.put("treeLevel", node.getInt("treeLevel") + 1);//節點等級 children.add(jsonObject); } } if (children.size() > 0) { node.put("spread", true);// 展開子節點 node.put("children", children);//加入子節點 //遞歸獲取子節點 getTreeChildren(node.getJSONArray("children"), listAll, parentId); } }