private String createTreeJson(List<SchedJob> list) { JSONArray rootArray = new JSONArray(); for (int i=0; i<list.size(); i++) { SchedJob resource = list.get(i); System.out.println(resource.getJobid()+"--------"+resource.getParentjobid()); //PARENT_JOB_ID=0 表示是根節點 if (resource.getParentjobid() == 0) { JSONObject rootObj = createBranch(list, resource); rootArray.add(rootObj); } } return rootArray.toString(); } /** * 遞歸建立分支節點Json對象 * @param list 建立樹的原始數據 * @param currentNode 當前節點 * @return 當前節點與該節點的子節點json對象 */ private JSONObject createBranch(List<SchedJob> list, SchedJob currentNode) { /* * 將javabean對象解析成爲JSON對象 */ JSONObject currentObj = JSONObject.fromObject(currentNode); JSONArray childArray = new JSONArray(); /* * 循環遍歷原始數據列表,判斷列表中某對象的父id值是否等於當前節點的id值, * 若是相等,進入遞歸建立新節點的子節點,直至無子節點時,返回節點,並將該 * 節點放入當前節點的子節點列表中 */ for (int i=0; i<list.size(); i++) { SchedJob newNode = list.get(i); if (newNode.getParentjobid()!=null && newNode.getParentjobid().compareTo(currentNode.getJobid()) == 0) { JSONObject childObj = createBranch(list, newNode); childArray.add(childObj); } } /* * 判斷當前子節點數組是否爲空,不爲空將子節點數組加入children字段中 */ if (!childArray.isEmpty()) { currentObj.put("children", childArray); } return currentObj; }
MySQL樹形查詢結果封裝成Json格式,返回給easyui treegridjava