方法1
/// <summary>
/// 根据Datatable得到Tree结构的JSON数据(去掉前12个字符,不能包括"")
/// </summary>
/// <param name="dt"></param>
/// <param name="pField"></param>
/// <param name="pValue"></param>
/// <param name="kField"></param>
/// <param name="TextField"></param>
/// <returns></returns>
public static string TableToEasyUITreeJson(DataTable dt, string pField, string pValue, string kField, string TextField)
{
StringBuilder sb = new StringBuilder();
string filter = String.Format(" {0}='{1}' ", pField, pValue);//获取顶级目录.
DataRow[] drs = dt.Select(filter);
if (drs.Length < 1)
return "";
sb.Append(","children":[");
foreach (DataRow dr in drs)
{
string pcv = dr[kField].ToString();
sb.Append("{");
sb.AppendFormat(""ID":"{0}",", dr[kField].ToString().Replace(""", "\""));
sb.AppendFormat(""text":"{0}"", dr[TextField].ToString().Replace(""", "\""));
sb.Append(TableToEasyUITreeJson(dt, pField, pcv, kField, TextField).TrimEnd(','));
sb.Append("},");
}
if (sb.ToString().EndsWith(","))
{
sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
return sb.ToString();
}
方法2:
private static string AddNode(string ParentID, int deep, DataSet ds)
{
string str = "";
DataView dvTree = new DataView(ds.Tables[0]);
dvTree.RowFilter = "[PID] ='" + ParentID + "'";//过滤出ParentId
int i = 0;
int d = deep;
foreach (DataRowView drv in dvTree)
{
if (i == 0)//如果是某一层的开始,需要“[”开始
{
if (d == 1)//如果深度为1,即第一层
str = "[";
else//否则,为第二层或更深
str = ","children":[";
}
else
str = str + ",";
str = str + "{";
str = str + ""ID":"" + drv["ID"] + "",";
str = str + ""text":"" + drv["Name"] + """;
str = str + AddNode(drv["ID"].ToString(), deep + 1, ds);//递归
str = str + "}";
i = i + 1;
if (dvTree.Count == i)//如果某一层到了末尾,需要"]"结束
str = str + "]";
}
return str;
}