在网上找了很久没有找到读取tree的java源码,所以只好自己写了一段了。因为自己本意不是想读取tree的数据源,而是想在左侧用accordion的方式显示菜单,所以只有两级,如果你想读三四级的,那你可以改进一下:
这是读取的源码:
public static String creatTree(List<Menu> menuList) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { List itemList; //用于临时储存子菜单 List result = new ArrayList(); //用于储存整体树行结构 String pid = "0"; //父级菜单的父id默认为0 Map map; //用于保存一个菜单及其子菜单 for (Menu menu : menuList) { if (menu.getPid().equals(pid)) { map = new HashMap(); map = BeanUtils.describe(menu); itemList = new ArrayList(); for (Menu menu1 : menuList) { if (menu1.getPid() == menu.getId()) { itemList.add(menu1); } } if(itemList.size()>0) //判断是否有子项 map.put("children", itemList); result.add(map); } else break; } return JSONArray.fromObject(result).toString();
这是返回的数据源格式:
[ { "id":"1", "pid":"0", "name":"pan", "children": [{"id":"4","name":"pan","pid":"1"},{"id":"5","name":"pan","pid":"1"}] }, { "id":"2", "pid":"0", "name":"pan", "children":[{"id":"6","name":"pan","pid":"2"},{"id":"7","name":"pan","pid":"2"}] }, { "id":"3", "pid":"0", "name":"pan" } ]
这里只读取了三个数据,当然还可以加别的需要的数据,如easyui 的icon,url等等