数据表结构
CREATE TABLE
CREATE TABLE [dbo].[Tb_Test](
[id] [int] NOT NULL,
[pid] [int] NULL,
[name] [nvarchar](50) NULL
)
.NET 后台方法
public static void getTreeJson(DataTable dt, ref string json, string pid)
{
//select t.id,t.pid,t.name from Tb_Test t where t.pid=0;
DataRow[] rows = dt.Select("pid='" + pid + "'");
string temp = string.Empty;
temp = "[";
foreach (DataRow dr in rows)
{
temp += string.Format("{{\"id\":{0},\"text\":\"{1}\",\"state\":\"open\",", dr["id"], dr["name"]);
//判断是否有子节点
if (dt.Select("pid='" + dr["id"].ToString() + "'").Length > 0)
{
temp += "\"children\":";
json += temp;
getTreeJson(dt, ref json, dr["id"].ToString());
temp = "";
}
json += temp;
if (json.EndsWith(","))
json = json.Remove(json.Length - 1, 1);
json += "},";
temp = "";
}
//子节结束 如北京下有朝阳和东城,东城结束时调用
if (json.EndsWith(","))
json = json.Remove(json.Length - 1, 1);
json += "]";
}
其中要注意的是json串中的text id 必须得加双引号,要不调用的时候树出不出来,找不原因弄了半天。