dataTable转换成Json格式

 #region dataTable转换成Json格式
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTableToJson(DataTable dt)
{
if (dt == null)
return string.Empty;
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (dt.Rows.Count > )
{
for (int i = ; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = ; j < dt.Columns.Count; j++)
{
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
if (j < dt.Columns.Count - )
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - )
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString();
} #endregion

或者

 private string GetJson(DataTable dt)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (DataRow row in dt.Rows)
{
sb.Append("{");
foreach (DataColumn column in dt.Columns)
{
string value = row[column.ColumnName].ToString();
value = formatStr(value);
sb.Append(column.ColumnName + ":\"" + value + "\",");
}
if (sb.ToString().EndsWith(","))
{
sb.Remove(sb.Length - , );
}
sb.Append("},");
}
if (sb.ToString().EndsWith(","))
{
sb.Remove(sb.Length - , );
}
sb.Append("]");
return sb.ToString();
} private string formatStr(string str)
{
if (str.Contains("\""))
{
str = str.Replace("\"", "");
}
if (str.Contains("\r\n"))
{
str = str.Replace("\r\n", "");
}
return str;
}
上一篇:将DataTable转换成Json格式


下一篇:数据库记录转换成json格式 (2011-03-13 19:48:37) (转)