1. 程式人生 > >Tree樹 遞歸查詢,顯示成JSON格式

Tree樹 遞歸查詢,顯示成JSON格式

獲取 tree map exce text ping recursion alt produce

首先想驗證自己的數據是不是JSON格式可以去 www.json.com 這個json格式檢測工具來檢測!!!

本地測試數據:

技術分享圖片

這是我本地查出來的數據:

技術分享圖片

轉換成json就是下面格式:

技術分享圖片

具體代碼:

需要的json包

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>

/**
* 遞歸查詢節點
*/
@RequestMapping(value="quertRecursionOrder",produces ="text/plain;charset=utf-8")
@ResponseBody
public JSONObject findTree(){
JSONObject jsonMap = new JSONObject();
try {
//查詢所有菜單 SELECT <include refid="RecursionScheam_Table"/> FROM recursion ORDER BY orders ASC
List<RecursionScheam> allMenu = treeService.quertRecursionOrder();
//根節點
List<RecursionScheam> rootMenu = new ArrayList<>();
for (RecursionScheam nav : allMenu) {
//父節點都是0
if(nav.getParentId().equals("0")){
rootMenu.add(nav);
}
}
//為根菜單設置子菜單,getClild是遞歸調用的
for (RecursionScheam recursionScheam : rootMenu) {
// 獲取根節點下的所有子節點 使用getChild方法
List<RecursionScheam> childList = getChild(recursionScheam.getId(),allMenu);
//給根節點設置子節點
recursionScheam.setChildMenus(childList);
}

jsonMap.put("list", rootMenu);
System.err.println(jsonMap.toString());
} catch (Exception e) {
// TODO: handle exception
}

return jsonMap;
}

/**
* 獲取子節點
* @param id 父節點id
* @param allMenu 所有菜單列表
* @return 每個根節點下,所有子菜單列表
*/
public List<RecursionScheam> getChild(String id,List<RecursionScheam> allMenu){
//子菜單
List<RecursionScheam> childList = new ArrayList<RecursionScheam>();
for (RecursionScheam nav : allMenu) {
// 遍歷所有節點,將所有菜單的父id與傳過來的根節點的id比較
//相等說明:為該根節點的子節點。
if(nav.getParentId().equals(id)){
childList.add(nav);
}
}
//遞歸
for (RecursionScheam navs : childList) {
navs.setChildMenus(getChild(navs.getId(),allMenu));
}
//如果節點下沒有子節點,返回一個空List(遞歸退出)
if(childList.size() == 0){
return new ArrayList<RecursionScheam>();
}
return childList;
}

Tree樹 遞歸查詢,顯示成JSON格式