如何将 JSONObject 转换为 java 中的 DefaultMutableTreeNode?

How would one convert a JSONObject into a DefaultMutableTreeNode in java?

我想创建一种像这样转换 JSONObject 的方法:

"master root" : {
    "folder 1" : {
        "folder 2" : {
            "example data" : "some more example values",
            "example data" : "some more examples"
        },
        "example data" : "example value"
    },
    "example data" : "lol"
}

像这样:

example tree image

我试过一个看起来像这样的方法:

public javax.swing.tree.DefaultMutableTreeNode createSingleTreeNode(JSONObject obj) {

    for(Iterator iterator = obj.keySet().iterator(); iterator.hasNext();) {

        String key = (String) iterator.next();

        if (obj.get(key) instanceof JSONObject) {

        javax.swing.tree.DefaultMutableTreeNode node1 = new javax.swing.tree.DefaultMutableTreeNode(key);

        node1.add(createSingleTreeNode((JSONObject) obj.get(key)));

        return node1;

        } else {

        return new javax.swing.tree.DefaultMutableTreeNode(key);

        }

    }

    return new javax.swing.tree.DefaultMutableTreeNode("");

}

它在某种程度上起作用,但在它到达第一个不是 json 对象的项目后停止,它只是停止并只添加一个。

关于如何正确执行此操作的任何想法? (我是 java 的新手,如果有图书馆已经这样做了,我很抱歉)

我修复了它,它不会返回节点,而是会将节点添加到您作为参数添加的 "master" 节点,这里是代码

public void createSingleTreeNode(JSONObject obj, javax.swing.tree.DefaultMutableTreeNode master) {

    javax.swing.tree.DefaultMutableTreeNode[] nodes = {};

    for(Iterator iterator = obj.keySet().iterator(); iterator.hasNext();) {

        String key = (String) iterator.next();

        if (obj.get(key) instanceof JSONObject) {

        javax.swing.tree.DefaultMutableTreeNode node1 = new javax.swing.tree.DefaultMutableTreeNode(key);

        LT.createSingleTreeNode((JSONObject) obj.get(key), node1);

        master.add(node1);

        } else {

        nodes = Arrays.copyOf(nodes, nodes.length + 1);

        nodes[nodes.length - 1] = new javax.swing.tree.DefaultMutableTreeNode(key);

        }

    }

    for (DefaultMutableTreeNode node : nodes) {

        master.add(node);

    }

}