Creating a tree using json from a list / table

Suppose in this case I have a table / list such as n = 3, but n can be unlimited.

groupid       answerid1     answerid2     answerid(n)
1              3            6             8 
1              3            6             9 
1              4            7               
2              5                            

and I want to create a parent / child json tree, e.g. using java. (I used GSON)

    {
        data: [
            {
                groupid: 1,
                children: [
                    {
                        answerid1: 1,
                        children: [
                            {
                                answerid2:3,
                                children: [
                                           {
                                    answerid3:6,
                                                  children: [
                                                              {answerid4: 8},
                                  {answerid4: 9} 
                                                             ]
                                              } 


                            }, {
                                 answerid2: 4,
                                 children: [
                                          {answerid3:7} 
                                   ]
                                 }
                                ]         
                    }, 

               {
                 groupid1: 2,
                 children: [
                       { answerid2: 5}
                        ]
                }

               ]      
        }

what will be the code / steps for this. I looked through a lot of tags, but mostly people print the output, rather than building a hashmap / ArrayList for GSON recursively for analysis and writing to the API. another point at which each identifier has other data associated with it that should be included in json output. for example, instead of {groupid: 1}, you would need this {groupid: 1, text = toyota}.

any help is much appreciated as I am pretty new to java as I come from the SAS background.

I get data like this (just a list matrix) Toyota, Gas, Compact, Corolla

Toyota, Gas, Compact, Camry Toyota, Hybrid, Compact, Prius Honda, Gas, Compact, Civic

If necessary, I can REFORM DATA into two tables

parentId parText answerId

1 Toyota 1 1 Toyota 2 1 Toyota 3 2 Honda 4

answerId level answerTextid answerText

1 1 1 Gas 1 2 2 Compact 1 3 3 Corolla 2 1 1 Gas 2 2 2 Compact 2 3 4 Camry ...

Then I need to make it a tree (a nested result similar to JSON readings with parent / child elements - just as if you were creating a file system directory)

one other tin that I would like to make is for each car a run like varialbe ({answerid3: 4, text = Corolla, run = 38}., but also, if I walk through a tree, give the average mile for the branch As they say in Toyota, Gas, Compact mileage will be avg (Camry, Corolla)

, - . , (hashmap)

{"data":[{"id":1,"children":
    [{"id": 2,"children":
        [{"id": 3 ,"children":
            [{"id": 4,"name":"Prius"}],"name":"Compact"}],"name":"Hybrid"},
    {"id":5,"children":
        [{"id":3,"children":
            [{"id":7,"MPG":38, "name":"Corolla"},
             {"id":8,"MPG":28,"name":"Camry"}],"name":"Compact"}],"name":"Gas"}],"name":"Toyota"},
{"id":9, "children":
    [{"id":10,"children":
        [{"id":3 ,"children":
            [{"id":11 ,"name":"Civic"}],"name":"Compact"}],"name":"Gas"}],"name":"Honda"}]}
+3
1

. , XML-, . , , , :

public class Test { 

    public static void main(String[] args) 
    {
        // hierarchical data in a flattened list
        String[][] data = {
                {"Toyota", "Gas", "Compact", "Corolla"},
                {"Toyota", "Gas", "Compact", "Camry"},
                {"Toyota", "Hybrid", "Compact", "Prius"},
                {"Honda", "Gas", "Compact", "Civic"}
        };

        TreeManager treeManager = new TreeManager();

        for(String[] row : data)
        {
            // build the path to our items in the tree
            List<String> path = new ArrayList<String>();
            for(String item : row)
            {
                // add this item to our path
                path.add(item);
                // will add it unless an Item with this name already exists at this path
                treeManager.addData(treeManager, path);
            }
        }

        treeManager.getData(data[0]).putValue("MPG", 38);
        treeManager.getData(data[1]).putValue("MPG", 28);

        Gson gson = new Gson();

        System.out.println(gson.toJson(treeManager));
    }

    /**
     * This base class provides the hierarchical property of
     * an object that contains a Map of child objects of the same type.
     * It also has a field - Name
     *
     */
    public static abstract class TreeItem implements Iterable<TreeItem>{

        private Map<String, TreeItem> children;     
        private String name;

        public TreeItem() {
            children = new HashMap<String, TreeItem>();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void addChild(String key, TreeItem data) 
        {           
            children.put(key, data);
        }

        public TreeItem getChild(String key) 
        {           
            return children.get(key);
        }

        public boolean hasChild(String key) 
        {           
            return children.containsKey(key);
        }

        @Override
        public Iterator<TreeItem> iterator() {          
            return children.values().iterator();
        }           
    }

    /**
     * This is our special case, root node. It is a TreeItem in itself
     * but contains methods for building and retrieving items from our tree
     *
     */
    public static class TreeManager extends TreeItem
    {       
        /**
         * Will add an Item to the tree at the specified path with the value
         * equal to the last item in the path, unless that Item already exists 
         */
        public void addData(List<String> path)
        {
            addData(this, path);
        }

        private void addData(TreeItem parent, List<String> path)
        {
            // if we're at the end of the path - create a node
            String data = path.get(0);
            if(path.size() == 1)
            {
                // unless there is already a node with this name
                if(!parent.hasChild(data))
                {
                    Group group = new Group();
                    group.setName(data);
                    parent.addChild(data, group);
                }
            }
            else
            {
                // pass the tail of this path down to the next level in the hierarchy
                addData(parent.getChild(data), path.subList(1, path.size()));
            }
        }

        public Group getData(String[] path)
        {
            return (Group) getData(this, Arrays.asList(path));
        }

        public Group getData(List<String> path)
        {
            return (Group) getData(this, path);
        }

        private TreeItem getData(TreeItem parent, List<String> path)
        {
            if(parent == null || path.size() == 0)
            {
                throw new IllegalArgumentException("Invalid path specified in getData, remainder: " 
                        + Arrays.toString(path.toArray()));
            }
            String data = path.get(0);
            if(path.size() == 1)
            {
                return parent.getChild(data);
            }
            else
            {
                // pass the tail of this path down to the next level in the hierarchy
                return getData(parent.getChild(data), path.subList(1, path.size()));
            }
        }
    }

    public static class Group extends TreeItem {

        private Map<String, Object> properties;

        public Object getValue(Object key) {
            return properties.get(key);
        }

        public Object putValue(String key, Object value) {
            return properties.put(key, value);
        }

        public Group () {
            super();
            properties = new HashMap<String, Object>();
        }       
    }
}

, , , MPG ( ...). - , (, "", "", "" ), (, ) , Object s, , . . , , Java.

Java, Object Orientated Programming, . , , , , . . .

+2

All Articles