今天有之前同事问我要datatable转json的方法,以前自己也弄过,但感觉网上有很多不靠谱的方法。所以自己在博客里记录一个,当然也是网上找的,但是这个靠谱一点,起码可以用不会报错,所以叫他靠谱的datatable转json方法~
public static string ToJson(DataTable dt) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { jsonString.Append("{ "); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType; jsonString.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type);//对特殊数据格式化,可以不用下面那两个方法,直接toString() if (j < dt.Columns.Count - 1) { jsonString.Append(strValue + ","); } else { jsonString.Append(strValue); } } jsonString.Append("},"); } jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } private static string StringFormat(string str, Type type) { if (type == typeof(string)) { str = String2Json(str); str = "\"" + str + "\""; } else if (type == typeof(DateTime)) { str = "\"" + str + "\""; } else if (type == typeof(bool)) { str = str.ToLower(); } else if (type != typeof(string) && string.IsNullOrEmpty(str)) { str = "\"" + str + "\""; } return str; } private static string String2Json(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s.ToCharArray()[i]; switch (c) { case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: sb.Append(c); break; } } return sb.ToString(); }