将DataTable里面的行转换成json字符串方法:
1 #region DataTable转为json 2 ///3 /// DataTable转为json 4 /// 5 /// DataTable 6 ///json数据 7 public static string DataTableToJson(DataTable dt) 8 { 9 List> list = (from DataRow dr in dt.Rows select dt.Columns.Cast ().ToDictionary(dc => dc.ColumnName, dc => dr[dc])).ToList();10 return SerializeToJson(list);11 } 12 #endregion13 14 #region 序列化对象为Json字符串15 /// 16 /// 序列化对象为Json字符串17 /// 18 /// 要序列化的对象19 /// 序列化对象的深度,默认为10020 ///Json字符串 21 public static string SerializeToJson(object obj, int recursionLimit = 100)22 {23 try24 {25 System.Web.Script.Serialization.JavaScriptSerializer serialize = new System.Web.Script.Serialization.JavaScriptSerializer();26 serialize.RecursionLimit = recursionLimit;27 return serialize.Serialize(obj);28 }29 catch { return ""; }30 } 31 #endregion32 33 #region json包转DataTable34 ///35 /// json包转DataTable36 /// 37 /// 38 ///39 public static DataTable JsonToDataTable(string jsons)40 {41 DataTable dt = new DataTable();42 try43 {44 System.Web.Script.Serialization.JavaScriptSerializer serialize = new System.Web.Script.Serialization.JavaScriptSerializer();45 serialize.MaxJsonLength = Int32.MaxValue;46 ArrayList list = serialize.Deserialize (jsons);47 if (list.Count > 0)48 {49 foreach (Dictionary item in list)50 {51 if (item.Keys.Count == 0)//无值返回空52 {53 return dt;54 }55 if (dt.Columns.Count == 0)//初始Columns56 {57 foreach (string current in item.Keys)58 {59 dt.Columns.Add(current, item[current].GetType());60 }61 }62 DataRow dr = dt.NewRow();63 foreach (string current in item.Keys)64 {65 dr[current] = item[current];66 }67 dt.Rows.Add(dr);68 }69 }70 }71 catch72 {73 return dt;74 }75 return dt;76 } 77 #endregion