/// <summary>         /// DataTable转成Json

/// </summary>         /// <param name="jsonName"></param>

/// <param name="dt"></param>         /// <returns></returns>

public static string DataTableToJson(string jsonName, DataTable dt)

{             StringBuilder Json = new StringBuilder();

Json.Append("{\"" + jsonName + "\":");

if (dt.Rows.Count > 0)

{

Json.Append("[");

for (int i = 0; i < dt.Rows.Count; i++)

{

Json.Append("{");

for (int j = 0; j < dt.Columns.Count; j++)

{

Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");

if (j < dt.Columns.Count - 1)

{

Json.Append(",");

}

}

Json.Append("}");

if (i < dt.Rows.Count - 1)

{

Json.Append(",");

}

}

Json.Append("]}");

}

else

{

Json.Append("\"null\"");

}

Json.Append("}");

return Json.ToString();

}

/// <summary>

/// DataTable转成Json

/// </summary>

/// <param name="jsonName"></param>

/// <param name="dt"></param>

/// <returns></returns>

public static string DataTableToJson(string jsonName, string GroupName, string strDataName, DataTable dt)

{

StringBuilder Json = new StringBuilder();

Json.Append("{\"" + jsonName + "\":[");

if (dt.Rows.Count > 0)

{

DataTable dtGroupNames = dt.DefaultView.ToTable(true, GroupName);

for (int m = 0; m < dtGroupNames.Rows.Count; m++)

{

//分组                     string strCurrentGroupValue = (dtGroupNames.Rows[m][GroupName] ?? "").ToString();

Json.Append("{\"" + GroupName + "\":\"" + strCurrentGroupValue + "\",\"" + strDataName + "\":[");

DataRow[] drs = dt.Select(GroupName + "='" + strCurrentGroupValue + "'");

for (int i = 0; i < drs.Length; i++)

{

Json.Append("{");

for (int j = 0; j < dt.Columns.Count; j++)

{

if (GroupName != dt.Columns[j].ColumnName.ToString() && (drs[i][GroupName] ?? "").ToString() == strCurrentGroupValue)                             {

//不构造已存在的分组信息

Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + drs[i][j].ToString() + "\"");

if (j < dt.Columns.Count - 1)

{

Json.Append(",");

}

}

}

Json.Append("}");

if (i < drs.Length - 1)

{

Json.Append(",");

}

}

Json.Append("]}");

if (m < dtGroupNames.Rows.Count - 1)

{

Json.Append(",");

}

}

}

Json.Append("]}");

return Json.ToString();

}

05-27 00:33