1.NewTonSoft.json
public static string DataTableToJson(DataTable dt) { if (dt == null && dt.Rows.Count <= 0) { return ""; } else { IsoDateTimeConverter convert = new IsoDateTimeConverter(); convert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; return JsonConvert.SerializeObject(dt, Formatting.None, convert); } }View Code
2.net frework 版本4.5以上
public static string Dtb2Json(DataTable dtb) { JavaScriptSerializer jss = new JavaScriptSerializer(); System.Collections.ArrayList dic = new System.Collections.ArrayList(); foreach (DataRow dr in dtb.Rows) { System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>(); foreach (DataColumn dc in dtb.Columns) { drow.Add(dc.ColumnName, dr[dc.ColumnName]); } dic.Add(drow); } //序列化 string jsonStr = jss.Serialize(dic); jsonStr = System.Text.RegularExpressions.Regex.Replace(jsonStr, @"\\/Date\((\d+)\)\\/", match => { DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return dt.ToString("yyyy-MM-dd HH:mm:ss"); }); return jsonStr; }View Code