1. 菜单实体类:
public class Menu {
private String id;
private String name;
private String parentId;
private String url;
private String icon;
private int order;
private List<Menu> children;
}
public Comparator<Menu> order(){
Comparator<Menu> comparator = new Comparator<Menu>() {
@Override
public int compare(Menu o1, Menu o2) {
if (o1.getOrder() != o2.getOrder()){
return o1.getOrder() - o2.getOrder();
}
return 0 ;
}
};
return comparator;
}
3. 生成树的方法:
public Map<String,Object> findTree(){
Map<String,Object> data = new HashMap<String,Object>();
try {
List<Menu> allMenu = menuDao.findTree();
List<Menu> rootMenu = new ArrayList<Menu>();
for (Menu nav : allMenu) {
if (nav.getParentId().equals( "0" )){
rootMenu.add(nav);
}
}
Collections.sort(rootMenu, order());
for (Menu nav : rootMenu) {
List<Menu> childList = getChild(nav.getId(), allMenu);
nav.setChildren(childList);
}
data.put( "success" , "true" );
data.put( "list" , rootMenu);
return data;
} catch (Exception e) {
data.put( "success" , "false" );
data.put( "list" , new ArrayList());
return data;
}
}
4. 获取子菜单:
public List<Menu> getChild(String id,List<Menu> allMenu){
List<Menu> childList = new ArrayList<Menu>();
for (Menu nav : allMenu) {
if (nav.ParentId().equals(id)){
childList.add(nav);
}
}
for (Menu nav : childList) {
nav.setChildren(getChild(nav.getId(), allMenu));
}
Collections.sort(childList,order());
if (childList.size() == 0 ){
return new ArrayList<Menu>();
}
return childList;
}
5. 最后返回的JSON串:
{
"success" : "true" ,
"list" : [
{
"id" : "1" ,
"name" : "Java" ,
"parentid" : "0" ,
"url" : "http://www.aliouchen.com" ,
"order" : 1 ,
"children" : [
{
"id" : "2" ,
"name" : "并发编程" ,
"parentid" : "1" ,
"url" : "http://www.aliouchen.com" ,
"order" : 1 ,
"children" : []
},
{
"id" : "3" ,
"name" : "多线程" ,
"parentid" : "1" ,
"url" : "http://www.aliouchen.com" ,
"order" : 2 ,
"children" : [
"id" : "4" ,
"name" : "Thread" ,
"parentid" : "3" ,
"url" : "http://www.aliouchen.com" ,
"order" : 1 ,
"children" :[]
]
}
]
},
{
"id" : "5" ,
"name" : "Python" ,
"parentid" : "0" ,
"url" : "http://www.aliouchen.com" ,
"order" : 2 ,
"children" : []
}
]
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步