gpt4 book ai didi

java - 如何在 java 中将 JSONObject 转换为 DefaultMutableTreeNode?

转载 作者:太空宇宙 更新时间:2023-11-04 09:24:35 24 4
gpt4 key购买 nike

我想创建一种方法来转换 JSONObject,如下所示:

"master root" : {
"folder 1" : {
"folder 2" : {
"example data" : "some more example values",
"example data" : "some more examples"
},
"example data" : "example value"
},
"example data" : "lol"
}

像这样:

example tree image

我尝试过一种看起来像这样的方法:

public javax.swing.tree.DefaultMutableTreeNode createSingleTreeNode(JSONObject obj) {

for(Iterator iterator = obj.keySet().iterator(); iterator.hasNext();) {

String key = (String) iterator.next();

if (obj.get(key) instanceof JSONObject) {

javax.swing.tree.DefaultMutableTreeNode node1 = new javax.swing.tree.DefaultMutableTreeNode(key);

node1.add(createSingleTreeNode((JSONObject) obj.get(key)));

return node1;

} else {

return new javax.swing.tree.DefaultMutableTreeNode(key);

}

}

return new javax.swing.tree.DefaultMutableTreeNode("");

}

它在某种程度上可以工作,但在到达第一个不是 json 对象的项目后停止,它只是停止并只添加一个。

关于如何正确执行此操作有什么想法吗? (我是java新手,所以如果已经有一个库可以做到这一点,我很抱歉)

最佳答案

我修复了它,它不会返回节点,而是将节点添加到您作为参数添加的“主”节点,这是代码

public void createSingleTreeNode(JSONObject obj, javax.swing.tree.DefaultMutableTreeNode master) {

javax.swing.tree.DefaultMutableTreeNode[] nodes = {};

for(Iterator iterator = obj.keySet().iterator(); iterator.hasNext();) {

String key = (String) iterator.next();

if (obj.get(key) instanceof JSONObject) {

javax.swing.tree.DefaultMutableTreeNode node1 = new javax.swing.tree.DefaultMutableTreeNode(key);

LT.createSingleTreeNode((JSONObject) obj.get(key), node1);

master.add(node1);

} else {

nodes = Arrays.copyOf(nodes, nodes.length + 1);

nodes[nodes.length - 1] = new javax.swing.tree.DefaultMutableTreeNode(key);

}

}

for (DefaultMutableTreeNode node : nodes) {

master.add(node);

}

}

关于java - 如何在 java 中将 JSONObject 转换为 DefaultMutableTreeNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com