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

160 views Asked by At

I want to create a way to convert a JSONObject like this:

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

to something like this:

example tree image

I have tried a method that looks something like this:

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

}

It works to some degree but stops after it gets to the first item that isn't a json object it just stops and only adds one.

Any ideas on how to do this properly? (I'm new to java so i'm sorry if there is a library that does this already)

1

There are 1 answers

0
HopefulProgrammer On BEST ANSWER

I fixed it, instead of returning the node, it will add the node to the "master" node that you add as a parameter, here is the code

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

    }

}