java生成多层树结构

我们经常会在网页,以及各种应用软件中见到多层树形结构。一般很多菜单,在数据库中存储时采用如下结构:

id:当前项id,value:当前项值(对应菜单名称),parentId:父亲菜单的id。

今天在这里向大家展示,如何讲这种数据,组织成json形式并且,传递给前台。这里不在展示同级菜单之间的排序了。

主要有三个类,多级菜单类,节点类,儿子类。代码如下:

//节点类
public class Node {
    public String id;
    public String value;
    public String parentId;

    private Children children = new Children();

    public String toString() {
        String result = "{" + "id : '" + id + "'" + ", text : '" + value + "'";

        if (children != null && children.getSize() != 0) {
            result += ", children : " + children.toString();
        } else {
            result += ", hasChildren: false";
        }

        return result + "}";
    }
     // 添加孩子节点
     public void addChild(Node node) {
     this.children.addChild(node);
     }
}

儿子类:

//孩子类
public class Children {

    private List<Node> list = new ArrayList<>();

    public int getSize() {
        return list.size();
    }

    public void addChild(Node node) {
        list.add(node);
    }

    // 拼接孩子节点的JSON字符串
    public String toString() {
        String result = "[";
        for (Iterator<Node> it = list.iterator(); it.hasNext();) {
            result += it.next().toString();
            result += ",";
        }
        result = result.substring(0, result.length() - 1);
        result += "]";
        return result;
    }
}

多级菜单类,这里数据我们为了方便采用模拟,真实情况从数据库查询获得。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class MultipleTree {

    public static List<HashMap<String, String>> getData() {

        List<HashMap<String, String>> list = new ArrayList<>();

        HashMap<String, String> hashMap1 = new HashMap<>();
        hashMap1.put("id", "1");
        hashMap1.put("value", "root");
        hashMap1.put("parentId", null);
        HashMap<String, String> hashMap2 = new HashMap<>();
        hashMap2.put("id", "2");
        hashMap2.put("value", "node1");
        hashMap2.put("parentId", "1");
        HashMap<String, String> hashMap3 = new HashMap<>();
        hashMap3.put("id", "3");
        hashMap3.put("value", "node2");
        hashMap3.put("parentId", "1");
        HashMap<String, String> hashMap4 = new HashMap<>();
        hashMap4.put("id", "5");
        hashMap4.put("value", "node1_1");
        hashMap4.put("parentId", "2");
        HashMap<String, String> hashMap5 = new HashMap<>();
        hashMap5.put("id", "6");
        hashMap5.put("value", "node2_1");
        hashMap5.put("parentId", "3");
        HashMap<String, String> hashMap6 = new HashMap<>();
        hashMap6.put("id", "7");
        hashMap6.put("value", "node2_2");
        hashMap6.put("parentId", "3");

        list.add(hashMap1);
        list.add(hashMap2);
        list.add(hashMap3);
        list.add(hashMap4);
        list.add(hashMap5);
        list.add(hashMap6);
        return list;

    }

    public static void main(String[] args) {

        // 获得数据,正式情况时,数据一般从数据库查询获得
        List<HashMap<String, String>> list = getData();

        // 跟节点
        Node root = null;
        // 存储节点对象
        HashMap<String, Node> hashMap = new HashMap<>();

        for (int i = 0; i < list.size(); i++) {
            Node node = new Node();
            HashMap<String, String> map = list.get(i);
            node.id = map.get("id");
            node.value = map.get("value");
            node.parentId = map.get("parentId");
            hashMap.put(node.id, node);
        }

        Set<String> set = hashMap.keySet();
        for (String s : set) {
            Node node = hashMap.get(s);
            if (node.parentId == null || node.parentId.equals("")) {  
                root = node;  
               } else {  
                hashMap.get(node.parentId).addChild(node);
               }  
        }
        
        System.out.println(root.toString());
    }

}

输出后的json数据如下(为了方便观看,格式化过):


{
    id: '1',
    text: 'root',
    children: [
        {
            id: '2',
            text: 'node1',
            children: [
                {
                    id: '5',
                    text: 'node1_1',
                    hasChildren: false
                }
            ]
        },
        {
            id: '3',
            text: 'node2',
            children: [
                {
                    id: '6',
                    text: 'node2_1',
                    hasChildren: false
                },
                {
                    id: '7',
                    text: 'node2_2',
                    hasChildren: false
                }
            ]
        }
    ]
}

ps:编程虽然不是我最喜欢的事,但写写还是挺好的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,552评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,255评论 4 61
  • 一切好像都如约而至,一切都好像从未开始。回忆起这段时光,我当时……很困惑也很迷茫,很快乐也很无奈,很清楚确却不知所...
    顾木阅读 294评论 1 1
  • 2017年3月26日 北京多云 久违的阳光如期降临北京,早上主日聚完,就和两个姊妹一起逛了下奥林公园(主要是这么好...
    JerryLi123阅读 300评论 0 0