您的位置:首页 > 编程语言 > Java开发

java 生成 树形结构数据(tree)

2017-04-25 19:21 621 查看
这里以bootstrap treeview为示例:

1、先看前端效果:http://jonmiles.github.io/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;
}


 最终效果图:



看过的大兄弟、小胸弟 给顶一下吧,也可以关注我的新浪微博:俺叫范小赖        随时联系我哦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息