/** * * @param rootList 根結點 * @param listAll 全部結點 * @param parentId 父子集依賴關係 * @param spread 有子結點是否展開 * <br> true 展開 * <br> false 不展開 * @return 樹形結構的字符串 */ public String getTreeByStack(List<?> rootList, List<?> listAll, String parentId,boolean spread){ JSONArray jsonRootList = JSONArray.fromObject(rootList); JSONArray jsonListAll = JSONArray.fromObject(listAll); Stack<JSONObject> stack=new Stack<JSONObject>(); for(int i=0;i<jsonRootList.size();i++){ JSONObject root=jsonRootList.getJSONObject(i); stack.push(root); } while (!stack.isEmpty()) { JSONObject parentNode=stack.pop(); JSONArray children=new JSONArray(); for(int j=0;j<jsonListAll.size();j++){ JSONObject jsonObject =jsonListAll.getJSONObject(j); if (jsonObject.getInt(parentId)==parentNode.getInt("id")) { children.add(jsonObject); } } if (children.size()>0) { parentNode.put("children", children); parentNode.put("spread", spread); JSONArray sunJsonArray=parentNode.getJSONArray("children"); for(int k=0;k<sunJsonArray.size();k++){ stack.push(sunJsonArray.getJSONObject(k)); } } } String tree=jsonRootList.toString(); return tree; }