java 生成 樹形結構資料(tree)
阿新 • • 發佈:2019-01-23
這裡以bootstrap treeview為示例:
2、前端效果中右鍵檢視原始碼,我們直接去看json資料是什麼樣滴~:
var json = '[' + '{' + '"text": "Parent 1",' + '"nodes": [' + '{' + '"text": "Child 1",' + '"nodes": [' + '{' + '"text": "Grandchild 1"' + '},' + '{' + '"text": "Grandchild 2"' + '}' + ']' + '},' + '{' + '"text": "Child 2"' + '}' + ']' + '},' + '{' + '"text": "Parent 2"' + '},' + '{' + '"text": "Parent 3"' + '},' + '{' + '"text": "Parent 4"' + '},' + '{' + '"text": "Parent 5"' + '}' + ']';
3、json資料分析:資料生成的時候,“text“ 對應的內容就是樹中顯示內容,然後設定“nodes”(子節點),子節點中又是先放入“text”,而後是“nodes”,這裡需要一個遞迴來完成,當沒有子節點的時候遞迴中斷。
4、我的資料表:(PARENT_ID ='' 為最高階父節點)
5、java遞迴程式碼:
public List<Map> getChildrens(List<Map> list) throws SystemException { //資料最終結果 List<Map> result = new ArrayList<Map>(); //1、迴圈最高階父節點資料 for(Map map : list){ Map tempMap = new HashMap(); //2、放入json資料 tempMap.put("text", map.get("ORG_NAME")); //3、判斷是否存在子節點 if(map.get("LEAF").equals("0")){ //4、根據父節點id獲取子節點 StringBuffer sb = new StringBuffer(); sb.append("SELECT * FROM `mst_org` org where org.PARENT_ID ='"+map.get("ORG_ID")+"' "); //5、調取自己迴圈獲取子節點 List<Map> childs = this.getChildrens(this.getDao().findBySql(sb.toString(), Map.class)); tempMap.put("nodes", childs); } result.add(tempMap); } return result; }
6、dao調取:
public List<Map> loadMstOrgForTree() throws SystemException { List<Map> result = new ArrayList<Map>(); //獲取頂級父節點 StringBuffer sb = new StringBuffer(); sb.append("SELECT * FROM `mst_org` org where org.PARENT_ID ='' "); List<Map> list = this.getChildrens(this.getDao().findBySql(sb.toString(), Map.class)); return list; }
最終效果圖:
看過的大兄弟、小胸弟 給頂一下吧,也可以關注我的新浪微博:俺叫範小賴 隨時聯絡我哦