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从数据库读出来了,大家还有更好的处理方法可以指出来,大家共同学习!
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从数据库读出来了,大家还有更好的处理方法可以指出来,大家共同学习!