C# Datatable轉成json串
阿新 • • 發佈:2018-12-14
#region datatable轉換json /ToJsonList(DataTable dt) /// <summary> /// datatable轉換json /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToJsonList(DataTable dt) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { jsonString.Append("{"); jsonString.Append("\"xh\":"); jsonString.Append((i + 1).ToString() + ","); 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); if (j < dt.Columns.Count - 1) { jsonString.Append(strValue + ","); } else { jsonString.Append(strValue); } } jsonString.Append("},"); } if (jsonString.Length > 1) { jsonString.Remove(jsonString.Length - 1, 1); } jsonString.Append("]"); string str = jsonString.ToString(); return jsonString.ToString(); } #endregion