C# ASP.NET递归循环生成嵌套json结构树
1. 建立用来保存树结构数据的目标对象
public class TreeObject { public string name { get; set; } public string value { get; set; } public IList<TreeObject> children = new List<TreeObject>(); public void Addchildren(TreeObject node) { this.children.Add(node); } }
2.查询表获得数据源
/// <summary> ///数据库的连接字符串 /// </summary> private static readonly string connstr = @"server=.;database=userInfo;uid=sa;pwd=123456";; public DataTable getTable(string cmdText) { using (SqlConnection cnn = new SqlConnection(connstr)) { using (SqlCommand comm = new SqlCommand(cmdText, cnn)) { comm.CommandType = CommandType.Text; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = comm; DataTable mytable = new DataTable(); da.Fill(mytable); return mytable; } } } public DataTable GetDataTable() { string sql = @"select ID,NAME_SHORT,BELONGTO_ID from UserInfo order by BELONGTO_ID"; DataTable dt = getTable(sql); return dt; }
3.递归循环生成树
//全局变量用于保存数据 public List<TreeObject> treeNodes = new List<TreeObject>(); //建立树的递归方法 /// </summary> /// <param name="dtSource">数据源</param> /// <param name="parentNode">父节点</param> /// <param name="parentID">节点的归属ID</param> public void BindTree(DataTable dtSource, TreeObject parentNode, string parentID) { DataRow[] rows = dtSource.Select(string.Format("BELONGTO_ID={0}", parentID)); foreach (DataRow row in rows) { TreeObject tree = new TreeObject(); tree.name = row["NAME_SHORT"].ToString(); tree.value = row["ID"].ToString(); //递归性质,函数内调用自身函数 BindTree(dtSource, tree, row["ID"].ToString()); //递归结束的终点条件 if (parentNode == null) { treeNodes.Add(tree); } else { parentNode.children.Add(tree); } } }
4.调用
//调用SQL,获取数据源 DataTable dt = GetDataTable(); //调用递归函数,传入数据源,根节点 BindTree(dt, null, "0"); //反序列化对象,生成json字符串 string jsonData = JsonConvert.SerializeObject(treeNodes); return jsonData;
5.效果
[{ "name": 'A', "value": '10000', "children": [{ "name": 'B1', "value": '10002', "children": [{ "children": [], "name": 'C', "value": '10007' }, { "children": [], "name": 'D', "value": '10008' }, { "children": [], "name": 'E', "value": '10009' } ] }, { "name": 'B2', "value": '10003', "children": [{ "children": [], "name": 'F', "value": '10010' }, { "children": [], "name": 'G', "value": '10011' } ] }, { "name": 'B3', "value": '10004', "children": [{ "children": [], "name": 'H', "value": '10012' }, { "children": [], "name": 'I', "value": '10013' }, { "children": [], "name": 'J', "value": '10014' } ] }, { "name": 'B4', "value": '10005', "children": [{ "children": [], "name": 'K', "value": '10015' }, { "name": 'L', "value": '10016', "children": [{ "children": [], "name": 'L1', "value": '10017' }, { "children": [], "name": 'L2', "value": '10018' } ] } ] } ] }]