下面的脚本创建了一张表:
[SQL] 纯文本查看 复制代码 CREATE TABLE Company
(
部门ID INT,
父级ID INT,
部门名称 VARCHAR(10)
)
INSERT INTO Company VALUES
(1,-1,'总部'),
(11,1,'财务中心'),
(12,1,'人力中心'),
(13,1,'信息中心'),
(111,11,'会计组'),
(112,11,'出纳组'),
(121,12,'薪酬组')
现通过递归查询得到了各个部门及各个部门的父部门:
[SQL] 纯文本查看 复制代码 WITH A AS(
SELECT 部门ID,父级ID,部门名称,部门名称 AS 父级部门名称
FROM Company
WHERE 父级ID=-1
UNION ALL
SELECT c.部门ID,c.父级ID,c.部门名称,p.部门名称 AS 父级部门名称
FROM A P
INNER JOIN Company c ON p.部门ID=c.父级ID
)
SELECT 部门ID,父级ID,部门名称,父级部门名称
FROM A
得到如下结果:
现在想用C#返回这样的JSON数据:
[JavaScript] 纯文本查看 复制代码 {
"deptName": "总部",
"deptId": 1,
"parentId": -1,
"children": [
{
"deptName": "财务中心",
"deptId": "11",
"parentId": "1",
"children": [
{
"deptName": "会计组",
"deptId": "111",
"parentId": "11"
},
{
"deptName": "出纳组",
"deptId": "112",
"parentId": "11"
}
]
},
{
"deptName": "人力中心",
"deptId": "12",
"parentId": "1",
"children": [
{
"deptName": "薪酬组",
"deptId": "121",
"parentId": "12"
}
]
},
{
"deptName": "信息中心",
"deptId": "13",
"parentId": "1"
}
]
}
请问用C#应该怎么处理成这样的格式,初学者请多多包涵,谢谢了~ |