Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an tree path to a json object

Tags:

java

json

tree

I have a tree with nodes like this:

-Root
|-Node 1
|-Node 2
  |-Node 2.1

one of these nodes are representet by one class

class Node {
    Integer id;
    String name;
    String route;
}

instances of the shown nodes are saved like

{id: 1, name: "Root", route:"1"}
{id: 2, name: "Node 1", route: "1/2"}
{id: 3, name: "Node 2", route: "1/3"}
{id: 4, name: "Node 2.1", route: "1/3/4"}

the question is: How can i get from a list of nodes to json representing the tree state, e.g.:

[{
"property": {
    "name": "Root",
    "id": "1",
    "route": "1"
},
"children": [{
    "property": {
        "name": "Node 1",
        "id": "2",
        "route": "1/2"
    },
    "property": {
        "name": "Node 2",
        "id": "3",
        "route": "1/3"
    },
    "children": [{
        "property": {
            "name": "Node 3",
            "id": "4",
            "route": "1/3/4"
        }
    }]
}]
}]

i need exactly this json structure

all this stuff have to be done in java. i tried to iterate over my list of nodes and built the json object, but i have problems to get the json structure from the route field of the nodes

i'm able to use a json library the node class is unchangable

EDIT: This format is quite strange, but needed. The "properties" are the nodes, if the "propertie" has children, they are not placed IN the propertie, ether AFTER the propertie... i think thats not quite sensefull but i cant change it

like image 221
Freak2000 Avatar asked Oct 24 '25 02:10

Freak2000


1 Answers

You could try an algorithm something like this:

public JSONObject toJSON(Node node, List<Node> others) {
    JSONObject json = new JSONObject();
    json.put("id", node.id); // and so on
    ...
    List children = new ArrayList<JSONObject>();
    for(Node subnode : others) {
        if(isChildOf(subnode, node)) {
            others.remove(subnode);
            children.add(toJSON(subnode, others));
        }
    }
    json.put("children", children);
    return json;
}

You are modifying a list as you iterate over it, and as recursive calls also iterate over it. This might be hairy, but try it. There are ways around it if it fails.

isChildOf() is the missing piece. That's some fairly basic string manipulation, to see whether subnode.path starts with node.id

Edit: actually this doesn't create the same structure as in your question. But I can't make much sense of the structure in your question. However something very similar to this algorithm will produce what you want. The principle is sound.

like image 50
slim Avatar answered Oct 26 '25 17:10

slim