ext 树状结构组成json格式

本文介绍了一种从数据库读取树状结构数据并转化为JSON格式的方法。通过使用双重循环和SQL查询,能够将多层级的数据关系正确地映射到JSON对象中。此方法适用于需要展示组织结构、文件系统等层次分明数据的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public JSONArray loadOasys() {


JSONArray root = new JSONArray(); //定义根的json数组
int i=0,j=0;
conn= super.getConnection();
conn1= super.getConnection(); //连接数据库
try {
stmt = conn.createStatement();
stmt1 = conn.createStatement(); //创造语句
String sql ="select * from oasystem";
result = stmt.executeQuery(sql);
while (result.next()) { //用双重循环 最外面的循环
if((result.getInt(2))==0) { //标记根节点
JSONObject json1 = new JSONObject(); //把第一层放入到json中
json1.put("id", result.getInt("id"))
.put("text", result.getString("text"))
.put("leaf", (result.getInt("leaf")==1 ? true :false));

result1 = stmt1.executeQuery(sql); //创造第二次的查询语句
JSONArray child= new JSONArray(); //把第二层放入到json数组中
while (result1.next()) { //进行第二次循环
if((result1.getInt(2)==result.getInt(1)) ) { //根据子节点对于的pid
JSONObject json2 = new JSONObject(); //用jsonObject去装子节点

json2.put("id", result1.getInt("id"))
.put("text", result1.getString("text"))
.put("leaf", (result1.getInt("leaf")==1 ? true :false));
child.put(i++, json2); //把子节点放入到jsonArray中
}
}
i=0;
json1.put("children", child); //把json数组放入到上一层的json数据中
root.put(j++,json1); //最终吧所以的每一个根节点放入到最后的根节点中
}
}
conn.close();
root.toJSONObject(root); //然后把jsonArray转换为jsonObject
return root; //返回一个jsonArray
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;


}
}
终于把树状结构用json从数据库读出来了,大家还有更好的处理方法可以指出来,大家共同学习!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值