#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("\r\n")) { str = str.Replace("\r\n", ""); } return str; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步