/// <summary>
/// 将dataTable数据构造成Json格式的字符串
/// </summary>
/// <param name="dt">数据集</param>
/// <returns></returns>
public string DataTable2Json(DataTable dt)
{
if (dt != null && dt.Rows.Count > 0)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
jsonBuilder.Append(string.Format("\"{0}\"",dt.TableName.ToString()));
jsonBuilder.Append(":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"" + dt.Columns[j].ColumnName + "\"");
jsonBuilder.Append(":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder = new StringBuilder(jsonBuilder.ToString().TrimEnd(','));
jsonBuilder.Append("},");
}
jsonBuilder = new StringBuilder(jsonBuilder.ToString().TrimEnd(','));
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
else
{
return string.Format("{\"{0}\":{}}", dt.TableName.ToString());
}
}