【发布时间】:2020-05-04 00:04:45
【问题描述】:
代码是:
public JSONArray tree_data() {
JSONArray result = new JSONArray();
JSONArray nodes = new JSONArray();
try {
String query= "select parent_names.name as parent_name, child_names.name as child_name, parent_child.title from parent_child INNER join parent_names on parent_names.id=parent_child.parent_id\r\n" +
" INNER join child_names on child_names.id=parent_child.child_id order by parent_names.name;";
Statement td = this.con.createStatement();
ResultSet rst=td.executeQuery(query);
String parent="";
int i=0;
while(rst.next())
{
JSONObject childs = new JSONObject();
JSONObject obj1 = new JSONObject();
String nowparent=rst.getString("parent_name");
if(parent.equals(nowparent)) {
childs.put("text",rst.getString("child_name"));
childs.put("title", rst.getString("title"));
nodes.put(childs);
}else {
parent=nowparent;
obj1.put("text", parent);
childs.put("text",rst.getString("child_name"));
childs.put("title", rst.getString("title"));
nodes.put(childs);
}obj1.put("nodes", nodes);
result.put(obj1);
}
}
catch (Exception e) {
System.out.print(e);
}
System.out.print(result);
return result;
}
我想要这个 JSON 输出
[
{
text: 'Order',
nodes: [
{
text: 'countrywise',
title: 'sss'
},
{
text: 'factorywise',
title: 'ffff'
}
]
},
{
text: 'sales',
nodes: [
{
text: 'countrywise',
title: 'sss'
},
{
text: 'factorywise',
title: 'ffff'
},
{
text: 'Season',
title: 'eeee'
}
]
}
];
这是数据库。
parent_name child_name title
命令,
西森,
sss, //
订单,客户,
cc, //
斯莱斯,
季节,
sssss, //
斯莱斯, 顾客, ssssds, //
斯莱斯, 国家, sssdsds
更多方法正在使用,但我无法解决它。我认为问题有一个循环,但没有显示这个循环中的问题。请帮助解决这个问题。谢谢
【问题讨论】:
-
我建议在 HashMap 中迭代存储数据时,键是您的 parent_name,并针对该键存储所有节点数据。
-
请重新格式化代表数据库表的文本并使其可读。
-
数据库中的数据似乎与您预期的 JSON 字符串不同。