#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 > 0) { 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("]"); 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 - 1, 1); } sb.Append("},"); } if (sb.ToString().EndsWith(",")) { sb.Remove(sb.Length - 1, 1); } sb.Append("]"); return sb.ToString(); } private string formatStr(string str) { if (str.Contains(""")) { str = str.Replace(""", ""); } if (str.Contains(" ")) { str = str.Replace(" ", ""); } return str; }