I have a csv file which has contents like :
Fruit, Mango
Fruit, Apple
Car, Audi
Apple, Red
Color, Brown
I want to eventually convert it in a format like this :
"hierarchy" : [{
"label": "Fruit",
"children" : [ {label: "Mango"}, {label: "Apple", "children": [ {label:"Red"}]}
]
},
{
"label" : "Car",
"children" : [ {label: "Audi"}
]
},
{
"label" : "Color",
"children" : [ {label: "Brown"}
]
}]
To do this, I have inserted the values in the map :
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String[] contents=(sb.toString().split("\n"));
String[] newContents;
Map<String, List<String>> myMaps = new LinkedHashMap<String, List<String>>();
for(String s : contents)
{
newContents= s.split(",");
if (!myMaps.containsKey(newContents[0])) {
myMaps.put(newContents[0], new ArrayList<String>());
}
myMaps.get(newContents[0]).add(newContents[1]);
}
This will basically convert the file to a map in the form of parent (key) and child (values). I was however wondering how to deal with the case when there is more than 1 level of depth - For example in my given csv? Will a map work in this case or is there a better approach?
Your JSON structure looks more like a tree, that can be desined as a class:
then hierarchy is an array or List of nodes
List is preferred over array, because it is easier to use during population of children
UPDATE: The full example on how to populate the Tree using
Node
class:Note: You do not need explicit
Node
, and you can useMap<String, Object>
where a value can contain nested maps, or List of children, or String value for label. But using an explicit class is cleaner.Alternative to recursive lookup for an existing node in the tree, an independent flat collection (Map) can be created to speed up lookups:
Just for reference: Full example
Try this.
result:
Map is fine. Just use recursive function to write deeper levels.