Java递归树,并返回JSONArray

@SuppressWarnings("unchecked")
	@Override
	public JSONArray queryMenu() {
		JSONArray array = new JSONArray();
		return queryMenuByParent(0,array);
	}
	
	/**
	 * 根据父节点ID获得子节点
	 * @param parendId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONArray queryMenuByParent(int parentId,JSONArray array){
		JSONObject obj = new JSONObject();
		Query q = factory.getCurrentSession().createSQLQuery("select * from Menu where ParentId="+parentId).setResultTransformer(Transformers.aliasToBean(Menu.class));
		List list = q.list();
		if(list!=null){
			for (int i = 0; i < list.size(); i++) {//节点遍历
				//System.out.println("节点id:"+list.get(i).getMenuId()+" "+list.get(i).getMenuName());
				obj.put("id", list.get(i).getMenuId());
				obj.put("name", list.get(i).getMenuName());
				obj.put("node", queryMenuByParent(list.get(i).getMenuId(),new JSONArray()));
				array.add(obj);
			}
		}
		return array;
	}

数据库:

--菜单表(Menu)
create table Menu(
MenuId int primary key identity(1,1) not null,-- 编号
ParentId int default(0) not null,-- 父级菜单编号(0为顶级菜单)
MenuName varchar(50) not null-- 菜单栏名称
)

数据库数据:

Java递归树,并返回JSONArray_第1张图片


调用方法queryMenu()方法即可,0是树的顶点编号。打印结果:

[{"id":1,"name":"学员信息管理","node":[]},{"id":2,"name":"基本信息设置","node":[{"id":7,"name":"部门设置","node":[{"id":8,"name":"查询","node":[]},{"id":9,"name":"增加","node":[]},{"id":10,"name":"修改","node":[]},{"id":11,"name":"删除","node":[]}]}]},{"id":3,"name":"资金管理","node":[]},{"id":4,"name":"其他功能","node":[]},{"id":5,"name":"系统管理中心","node":[]},{"id":6,"name":"人力资源","node":[]}]


你可能感兴趣的:(Java)