首页 > 代码库 > 将树形结构生成Json字符串

将树形结构生成Json字符串

 1 /// <summary> 2         /// 将树形结构生成Json字符串 3         /// </summary> 4         /// <param name="dt">传入的树形结构DataTable</param> 5         /// <param name="childColumnName">子级ID列名</param> 6         /// <param name="parentColumnName">父级ID列名</param> 7         /// <param name="textColumnName">内容列列名</param> 8         /// <param name="Id">指定的需要进行查询的顶级节点的ID</param> 9         /// <returns>此方法的返回会在前方多出",children:"这样10个长度的字符串,使用时去掉即可</returns>10         public static string GetTreeJson(DataTable dt, string childColumnName, string parentColumnName, string textColumnName, int Id)11         {12             StringBuilder sb = new StringBuilder();13             DataRow[] drs = dt.Select(parentColumnName + "=" + Id);14             if (drs.Length < 1)15                 return "";16             sb.Append(",children:[");17             foreach (DataRow dr in drs)18             {19                 sb.Append("{");20                 sb.AppendFormat("id:{0},", dr[childColumnName].ToString());21                 sb.AppendFormat("text:‘{0}‘", dr[textColumnName].ToString());22                 sb.Append(GetTreeJson(dt, childColumnName, parentColumnName, textColumnName, (int)dr[childColumnName]).TrimEnd(,));23                 sb.Append("},");24             }25             if (sb.ToString().EndsWith(","))26             {27                 sb.Remove(sb.Length - 1, 1);28             }29             sb.Append("]");30             return sb.ToString();31         }

使用时str = str.Substring(10); 去掉前10个长度的字符串

将树形结构生成Json字符串