我有一个csv文件,其内容如下:
Fruit, Mango
Fruit, Apple
Car, Audi
Apple, Red
Color, Brown
我想最终以这样的格式转换它:
"hierarchy" : [{
"label": "Fruit",
"children" : [ {label: "Mango"}, {label: "Apple", "children": [ {label:"Red"}]}
]
},
{
"label" : "Car",
"children" : [ {label: "Audi"}
]
},
{
"label" : "Color",
"children" : [ {label: "Brown"}
]
}]
为此,我在地图中插入了值:
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]);
}
这基本上将文件转换为父(键)和子(值)形式的映射。然而,我想知道如何处理超过1级深度的情况 - 例如在我给定的csv中?地图会在这种情况下起作用还是有更好的方法?
答案 0 :(得分:1)
您的JSON结构看起来更像一棵树,可以被视为一个类:
public class Node {
private String label;
private List<Node> children; // can also be of type Node[]
// getters, setters
}
然后层次结构是一个数组或节点列表
列表比数组更受欢迎,因为它在儿童群体中更容易使用
更新:
有关如何使用Node
类填充树的完整示例:
public class Node {
private String label;
private List<Node> children = new ArrayList<>(); // to avoid checks for null
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;
}
}
class Converter {
public List<Node> fromCsvFile(String filename) throws IOException {
Node root = new Node();
BufferedReader input = new BufferedReader(new FileReader(filename));
String[] entry;
String line = input.readLine();
while (line != null) {
entry = line.split(",");
// find or create
Node node = findByLabel(root, entry[0]);
if (node == null) {
// top level
node = new Node();
node.setLabel(entry[0]);
root.getChildren().add(node);
}
// add child
Node child = new Node();
child.setLabel(entry[1]);
node.getChildren().add(child);
// next line
line = input.readLine();
}
return root.getChildren();
}
public Node findByLabel(Node node, String label) {
if (label.equals(node.getLabel())) {
return node;
}
for (Node child : node.getChildren()) {
// recursion
Node found = findByLabel(child, label);
if (found != null) {
return found;
}
}
return null;
}
}
注意:您不需要显式Node
,并且您可以使用Map<String, Object>
,其中值可以包含嵌套映射,或子列表,或者标签的字符串值。但使用明确的类更清晰。
除了树中现有节点的递归查找之外,还可以创建一个独立的平面集合(Map)来加速查找:
class Converter {
public List<Node> fromCsvFile(String filename) throws IOException {
Node root = new Node();
Map<String, Node> existingNodes = new HashMap<>();
BufferedReader input = new BufferedReader(new FileReader(filename));
String[] entry;
String line = input.readLine();
while (line != null) {
entry = line.split(",");
// find or create
Node node = existingNodes.get(entry[0]);
if (node == null) {
// new top level node
node = new Node();
node.setLabel(entry[0]);
root.getChildren().add(node);
existingNodes.put(entry[0], node);
}
// add child
Node child = new Node();
child.setLabel(entry[1]);
node.getChildren().add(child);
existingNodes.put(entry[1], child);
// next line
line = input.readLine();
}
return root.getChildren();
}
}
仅供参考:Full example
答案 1 :(得分:0)
地图很好。只需使用递归函数来编写更深层次。
答案 2 :(得分:0)
试试这个。
String csv = ""
+ "Fruit, Mango\n"
+ "Fruit, Apple\n"
+ "Car, Audi\n"
+ "Apple, Red\n"
+ "Color, Brown\n"
+ "Red, Fire\n";
Set<String> topLevels = new LinkedHashSet<>();
Set<String> notTopLevels = new LinkedHashSet<>();
Map<String, Map<String, Object>> labels = new LinkedHashMap<>();
try (BufferedReader reader = new BufferedReader(new StringReader(csv))) {
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\\s*,\\s*");
Map<String, Object> value = labels.computeIfAbsent(
fields[1], k -> new LinkedHashMap<String, Object>());
labels.computeIfAbsent(
fields[0], k -> new LinkedHashMap<String, Object>())
.put(fields[1], value);
topLevels.add(fields[0]);
notTopLevels.add(fields[1]);
}
}
Map<String, Object> hierarchy = new LinkedHashMap<>();
topLevels.removeAll(notTopLevels);
for (String s : topLevels)
hierarchy.put(s, labels.get(s));
System.out.println(hierarchy);
结果:
{Fruit={Mango={}, Apple={Red={Fire={}}}}, Car={Audi={}}, Color={Brown={}}}