1

我想创建一种像这样转换 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"
}

像这样:

示例树图像

我尝试了一种看起来像这样的方法:

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新手,所以如果有一个库已经这样做了,我很抱歉)

4

1 回答 1

0

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

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);

    }

}
于 2019-09-12T22:24:07.990 回答