Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import com.google.gson.GsonBuilder;
- public class Converter {
- public static void main(String[] args) throws IOException {
- final Map<String, Object> holder = new HashMap<>();
- holder.put("hierarchy", fromCsvFile("mapping.csv"));
- System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(holder));
- }
- public static class Node {
- private String label;
- private List<Node> children;
- public String getLabel() {
- return label;
- }
- public void setLabel(String label) {
- this.label = label;
- }
- public List<Node> getChildren() {
- return children;
- }
- public void setChildren(List<Node> children) {
- this.children = children;
- }
- public void addChild(Node child) {
- if (children == null) {
- children = new ArrayList<>();
- }
- children.add(child);
- }
- }
- public static List<Node> fromCsvFile(String filename) throws IOException {
- Node root = new Node();
- Map<String, Node> existingNodes = new HashMap<>();
- try (BufferedReader input = new BufferedReader(new FileReader(filename))) {
- String parentName, childName;
- String[] entry;
- String line = input.readLine();
- while (line != null) {
- entry = line.split(",");
- parentName = entry[0].trim();
- childName = entry[1].trim();
- // find or create
- Node node = existingNodes.get(parentName);
- if (node == null) {
- // new top level node
- node = new Node();
- node.setLabel(parentName);
- root.addChild(node);
- existingNodes.put(parentName, node);
- }
- // add child
- Node child = new Node();
- child.setLabel(childName);
- node.addChild(child);
- existingNodes.put(childName, child);
- // next line
- line = input.readLine();
- }
- }
- return root.getChildren();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement