1 //1、核心代碼遞歸實現組裝數形數據 2 public String getResourceTreeToJson() { 3 return this.createTreeJson(findAll());//findAll()是全查select * from tableName 4 } 5 6 /... ...
1 //1、核心代碼遞歸實現組裝數形數據 2 public String getResourceTreeToJson() { 3 return this.createTreeJson(findAll());//findAll()是全查select * from tableName 4 } 5 6 /** 7 * 生成josn 8 * @param list 9 * @return 10 */ 11 private String createTreeJson(List<Resource> list) { 12 JSONArray rootArray = new JSONArray(); 13 for (Resource resource : list) { 14 if (resource.getParentid() == null) { 15 JSONObject rootObj = createBranch(list, resource); 16 rootArray.add(rootObj); 17 } 18 } 19 return rootArray.toString(); 20 } 21 22 /** 23 * 遞歸遍歷找到當前節點的所有子節點 24 * @param list 25 * @param currentNode 26 * @return 27 */ 28 private JSONObject createBranch(List<Resource> list, Resource currentNode) { 29 JSONObject currentObj = JSONObject.fromObject(currentNode); 30 JSONArray childArray = new JSONArray(); 31 for (Resource newNode : list) { 32 if (newNode.getParentid() != null && newNode.getParentid().compareTo(currentNode.getId()) == 0) { 33 JSONObject childObj = createBranch(list, newNode); 34 childArray.add(childObj); 35 } 36 } 37 if (!childArray.isEmpty()) { 38 currentObj.put("children", childArray); 39 } 40 return currentObj; 41 }
//2、使用ztree實現樹形數據簡單無需用遞歸組裝,簡單方便
1 select 2 dep.dep_id, 3 dep.prv_id, 4 dep.dep_code, //主要返回 5 dep.dep_name, //主要返回 6 dep2.dep_name as parent_Name, 7 dep2.dep_code AS parent_Code,//主要返回 8 dep.dep_order, 9 dep.dep_state 10 from sys_department dep 11 LEFT JOIN sys_department dep2 12 on dep.pdep_id = dep2.dep_id 13 14 15 主要返回的對應ztree的id、pId、name,其它屬性可自定義,ztree會自動識別組裝樹形節點的數據;
還有就是實體bean中的屬性除了定義資料庫中的列屬性之外,還應該把ztree中的節點屬性也定義上