我要求将数据从excel转换为树结构。因为我将使用EXTJS树面板,所以我需要将java对象存储为JSON格式:
Logic
---Propositional Logic
---Predicate Logic
---Modal Logic
-------Stit logic
-------Doxastic logic
---Temporal logic
我从excel表读取数据并使用multimap将每个键与多个值相关联。 存储在多地图后的我的i / p:[逻辑=>命题逻辑,谓词,模态,时间] [模态逻辑= stit,doxastic]
在stackoverflow论坛中搜索时,我发现了一个示例代码,如下所示: 我在这个函数中发送了multimap。我试图将它用于我的目标并添加gson代码以进行测试。
public static Set <Tree> transform(Map <String, List<String>> input) {
// Potential tree roots. We start with all LHS keys as potential roots,
// and eliminate them when we see their keys on the RHS.
Set<String> roots = new HashSet<String>(input.keySet());
// This map associates keys with the tree nodes that we create for them
Map<String, Tree> map = new HashMap<String, Tree>();
Gson gs = new Gson();
String jsonString = null;
for (Map.Entry<String, List<String>> entry : input.entrySet()) {
String key = entry.getKey();
List<String> childKeys = entry.getValue();
Tree tree = map.get(key);
if (tree == null) {
tree = new Tree(key);
map.put(key, tree);
}
for (String childKey : childKeys) {
roots.remove(childKey);
Tree child = map.get(childKey);
if (child == null) {
child = new Tree(childKey);
map.put(childKey, child);
}
tree.addChild(child);
jsonString =gs.toJson(tree);
}
System.out.println(jsonString);
}
Set<Tree> res = new HashSet<Tree>(roots.size());
for (String key : roots) {
res.add(map.get(key));
}
return res;
}
我也有一个Tree类:
public class Tree{
private String key;
private boolean leaf;
private List<Tree> children = new ArrayList<Tree>();
public Tree(String key)
{
this.key=key;
leaf=true;
}
public void addChild(Tree child)
{
children.add(child);
leaf=false;
}
}
我得到的是:
{"key":"Logic","leaf":false,"children":[{"key":"Propositional Logic","leaf":true,"children":[]},{"key":"Predicate Logic","leaf":true,"children":[]},{"key":"Modal Logic","leaf":true,"children":[]},{"key":"Temporal Logic","leaf":true,"children":[]}]}
{"key":"Modal Logic","leaf":false,"children":[{"key":"STIT logic","leaf":true,"children":[]},{"key":"Doxastic Logic","leaf":true,"children":[]}]}
但我想要o / p就像:
{"key":"Logic","leaf":false,"children":[{"key":"Propositional Logic","leaf":true,"children":[]},{"key":"Predicate Logic","leaf":true,"children":[]},{"key":"Modal Logic","leaf":true,"children":[{"key":"STIT logic","leaf":true,"children":[]},{"key":"Doxastic Logic","leaf":true,"children":[]},{"key":"Coalition Logic","leaf":true,"children":[]}},{"key":"Temporal Logic","leaf":true,"children":[]}]}
我对Java编程不是很熟悉所以我对此感到困惑。在上面的代码中应该添加什么,请您建议吗?
由于