using System; using System.Collections.Generic; using System.Data; using System.Text; namespace Common { public class JsonHelper { /// <summary> /// DataTable 转 Json /// </summary> /// <param name="dt">DataTable</param> /// <param name="fromCount">来自的行数</param> /// <param name="totalCountStr">总行数</param> /// <param name="tbname">表名</param> /// <returns></returns> public static string DT2JSON(DataTable dt, string tbname) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{\"" + tbname + "\":["); for (int i = 0; i < dt.Rows.Count; i++) { if (i > 0) jsonBuilder.Append(","); jsonBuilder.Append("{"); jsonBuilder.Append("\"no\":\"" + i + "\","); for (int j = 0; j < dt.Columns.Count; j++) { if (j > 0) jsonBuilder.Append(","); if (dt.Columns[j].DataType.Equals(typeof(DateTime)) && dt.Rows[i][j].ToString() != "") jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\": \"" + Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd HH:mm:ss") + "\""); else if (dt.Columns[j].DataType.Equals(typeof(String))) jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\": \"" + dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>") + "\""); else jsonBuilder.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\": \"" + dt.Rows[i][j].ToString() + "\""); } jsonBuilder.Append("}"); } jsonBuilder.Append("]}"); return jsonBuilder.ToString(); } } }