关于有层级关系时返回前端树状json
Posted flz-0429
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于有层级关系时返回前端树状json相关的知识,希望对你有一定的参考价值。
结果 { "message": [ { "children": [ { "children": [ { "children": [ { "empno": "7876", "ename": "ADAMS", "mgr": "7788", "sal": "1100" } ], "empno": "7788", "ename": "SCOTT", "mgr": "7566", "sal": "3000" }, { "children": [ { "empno": "7369", "ename": "SMITH", "mgr": "7902", "sal": "800" } ], "empno": "7902", "ename": "FORD", "mgr": "7566", "sal": "3000" } ], "empno": "7566", "ename": "JONES", "mgr": "7839", "sal": "2975" }, { "children": [ { "empno": "7499", "ename": "ALLEN", "mgr": "7698", "sal": "1600" }, { "empno": "7521", "ename": "WARD", "mgr": "7698", "sal": "1250" }, { "empno": "7654", "ename": "MARTIN", "mgr": "7698", "sal": "1250" }, { "empno": "7844", "ename": "TURNER", "mgr": "7698", "sal": "1500" }, { "empno": "7900", "ename": "JAMES", "mgr": "7698", "sal": "950" } ], "empno": "7698", "ename": "BLAKE", "mgr": "7839", "sal": "2850" }, { "children": [ { "empno": "7934", "ename": "MILLER", "mgr": "7782", "sal": "1300" } ], "empno": "7782", "ename": "CLARK", "mgr": "7839", "sal": "2450" } ], "empno": "7839", "ename": "KING", "mgr": "0", "sal": "5000" } ] }
1:数据库为Oracle的emp表找出King的所有下属
<select id="testBigDecimal25" resultType="com.mayi.vo.Menu"> select empno, ename, sal, mgr from emp </select>
一个javaBean
public class Menu { private String empno; private String ename; private String sal; private String mgr; //菜单标识 // private Meta meta; //子菜单 private List<Menu> children; get set自补
递归查子
public JSONObject getInfo() { System.out.println("iiiii"); List<Menu> list=dao.testBigDecimal24(s1.concat(".testBigDecimal25"), null); System.out.println(list); //调用TreeTest工具类方法生成树形结构的List集合 List<Menu> treeList = TreeUtil.listToTree(list); //使用fastjson对树形list件序列化转成json字符串,过滤掉属性值为null的属性 String message = JSON.toJSONString(treeList,SerializerFeature.PrettyFormat); JSONObject returnData = new JSONObject(); //重新将json字符串转成jsonObject对象,返回给前端 returnData.put("message",JSON.parse(message)); //return CommonUtil.successJson(returnData); return returnData; }
utils
//用List构建带有层次结构的json数据 //List父子节点构造树形Json public class TreeUtil { //将list集合转成树形结构的list集合 public static List<Menu> listToTree(List<Menu> list) { //用递归找子。 List<Menu> treeList = new ArrayList<Menu>(); for (Menu tree : list) { if (tree.getMgr().equals("0")) { //这个地方注意报空指针====== treeList.add(findChildren(tree, list)); } } return treeList; } //寻找子节点 private static Menu findChildren(Menu tree, List<Menu> list) { for (Menu node : list) { if (node.getMgr().equals(tree.getEmpno())) { if (tree.getChildren() == null) { tree.setChildren(new ArrayList<Menu>()); } tree.getChildren().add(findChildren(node, list)); } } return tree; } }
以上是关于关于有层级关系时返回前端树状json的主要内容,如果未能解决你的问题,请参考以下文章