/** * 得到菜单的json串 * 构造多叉树来实现一次加载多级所有的菜单 */ @SuppressWarnings({ "rawtypes" }) @Override public String getJsonstr() throws Exception { BsMenuExample example = new BsMenuExample(); example.setOrderByClause(" menulevel desc ,menuorder desc "); List<BsMenu> dataList= bsMenuDAO.selectByExample(example); // 节点列表(散列表,用于临时存储节点对象) HashMap<Integer,MenuNode> nodeList = new HashMap<Integer,MenuNode>(); // 根节点 MenuNode root = null; // 根据结果集构造节点列表(存入散列表) for (BsMenu dataRecord: dataList) { MenuNode node = new MenuNode(); node.setId(dataRecord.getId()); BeanUtils.copyProperties(dataRecord, node); nodeList.put(node.getId().intValue(), node); } // 构造无序的多叉树 Set entrySet = nodeList.entrySet(); for (Iterator it = entrySet.iterator(); it.hasNext();) { MenuNode node = (MenuNode) ((Map.Entry) it.next()).getValue(); if (node.getMenuparent() == null || node.getMenuparent().equals("")) { root = node; } else { ((MenuNode) nodeList.get(node.getMenuparent())).getChildren().add(node); } } String json =JSON.toJSONString(root); return "["+json+"]"; }
文章出自:http://www.oschina.net/code/snippet_142385_34771