#region 转换Table为JSON数据
/// <summary>
/// 转换Table为JSON数据
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string TableToJson(DataTable dt)
{
StringBuilder sb = new StringBuilder("[");
foreach (DataRow row in dt.Rows)
{
if (!row.Equals(dt.Rows[])) sb.Append(",");
sb.Append("{");
foreach (DataColumn col in dt.Columns)
{
if (!col.Equals(dt.Columns[])) sb.Append(",");
string value = GetText(row, col.ColumnName);
if (string.IsNullOrEmpty(value)) continue; //跳过为空的数据
sb.Append("\"").Append(col.ColumnName).Append("\":\"").Append(value).Append("\"");
}
sb.Append("}");
}
sb.Append("]");
return sb.ToString();
}
/// <summary>
/// 从datable中读取文本
/// </summary>
/// <param name="row"></param>
/// <param name="col"></param>
/// <returns></returns>
private static string GetText(DataRow row, string col)
{
return row.IsNull(col) ? string.Empty : row[col].ToString();
}
#endregion