java 递归数据库生成 树形结构问题

成功:{"result":1,data:[{"ID":"1","Name":"年级1",child:[{"ID":"1","Name":"班级1"}]}]}如图所示,每条... 成功:{"result":1,data:[{"ID":"1","Name ":"年级1",child:[{ "ID":"1","Name ":"班级1"}]}]}
如图所示,每条数据都有一个parentinnercode对应branchinnercode
现在要生成json属性结构,
展开
 我来答
WENGYANYING26
2016-07-31 · TA获得超过365个赞
知道小有建树答主
回答量:626
采纳率:40%
帮助的人:176万
展开全部
1、渗正准备表结构及对应的表数据
a、表结构:
create table TB_TREE
(
CID NUMBER not null,
CNAME VARCHAR2(50),
PID NUMBER //父节点
)

b、表数据:

insert into tb_tree (CID, CNAME, PID) values (1, '中国'答喊汪, 0);
insert into tb_tree (CID, CNAME, PID) values (2, '北京市', 1);
insert into tb_tree (CID, CNAME, PID) values (3, '广东省', 1);
insert into tb_tree (CID, CNAME, PID) values (4, '上海市', 1);
insert into tb_tree (CID, CNAME, PID) values (5, '广州市', 3);
insert into tb_tree (CID, CNAME, PID) values (6, '深圳市', 3);
insert into tb_tree (CID, CNAME, PID) values (7, '海珠区', 5);
insert into tb_tree (CID, CNAME, PID) values (8, '天河区', 5);
insert into tb_tree (CID, CNAME, PID) values (9, '福田区', 6);
insert into tb_tree (CID, CNAME, PID) values (10, '南山区', 6);
insert into tb_tree (CID, CNAME, PID) values (11, '密云县', 2);
insert into tb_tree (CID, CNAME, PID) values (12, '浦东', 4);

2、TreeNode对象,对应tb_tree

public class TreeNode implements Serializable {
private Integer cid;
private String cname;
private Integer pid;
private List nodes = new ArrayList();

public TreeNode() {
}

//getter、setter省略清仔
}

3、测试数据

public class TreeNodeTest {
@Test
public void loadTree() throws Exception{
System.out.println(JsonUtils.javaToJson(recursiveTree(1)));
}

/**
* 递归算法解析成树形结构
*
* @param cid
* @return
* @author jiqinlin
*/
public TreeNode recursiveTree(int cid) {
//根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
TreeNode node = personService.getreeNode(cid);
//查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
List childTreeNodes = personService.queryTreeNode(cid);
//遍历子节点
for(TreeNode child : childTreeNodes){
TreeNode n = recursiveTree(child.getCid()); //递归
node.getNodes().add(n);
}

return node;
}
}

输出的json格式如下:

{
"cid": 1,
"nodes": [
{
"cid": 2,
"nodes": [
{
"cid": 11,
"nodes": [

],
"cname": "密云县",
"pid": 2
}
],
"cname": "北京市",
"pid": 1
},
{
"cid": 3,
"nodes": [
{
"cid": 5,
"nodes": [
{
"cid": 7,
"nodes": [

],
"cname": "海珠区",
"pid": 5
},
{
"cid": 8,
"nodes": [

],
"cname": "天河区",
"pid": 5
}
],
"cname": "广州市",
"pid": 3
},
{
"cid": 6,
"nodes": [
{
"cid": 9,
"nodes": [

],
"cname": "福田区",
"pid": 6
},
{
"cid": 10,
"nodes": [

],
"cname": "南山区",
"pid": 6
}
],
"cname": "深圳市",
"pid": 3
}
],
"cname": "广东省",
"pid": 1
},
{
"cid": 4,
"nodes": [
{
"cid": 12,
"nodes": [

],
"cname": "浦东",
"pid": 4
}
],
"cname": "上海市",
"pid": 1
}
],
"cname": "中国",
"pid": 0
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式