C#中datatable序列化与反序列化实例分析
投稿:shichen2014
这篇文章主要介绍了C#中datatable序列化与反序列化,是datatable的常用技巧,需要的朋友可以参考下
本文实例讲述了C#中datatable序列化与反序列化,分享给大家供大家参考。具体方法如下:
一、datatable序列化
public string getSendDetailQuery(DateTime timeS, DateTime timeE, string sccount) { try { SmsOperate so = new SmsOperate(); //得到dt DataTable dtt = so.getSendDetailQuery(timeS, timeE, sccount); JavaScriptSerializer serializer = new JavaScriptSerializer(); string aaa = Serialize(dtt, false);//datatable不能直接序列化,此为序列化方法 return "0:" + aaa; } catch (Exception e) { return "-1" + e.Message; } } /// <summary>序列化方法 /// 不需要分页 /// </summary> /// <param name="dt"></param> /// <param name="flag">false</param> /// <returns></returns> public string Serialize(DataTable dt, bool flag) { JavaScriptSerializer serializer = new JavaScriptSerializer(); List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> result = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { result.Add(dc.ColumnName, dr[dc].ToString()); } list.Add(result); } return serializer.Serialize(list); ; }
二、datatable反序列化
public DataTable getSendDetailTest() { DataTable dtb = new DataTable(); //得到序列化结果aaa string aaa = getSendDetailQuery(Convert.ToDateTime("2012-01-01 00:00:00"), Convert.ToDateTime("2012-05-01 23:59:59"), "wangsub1"); if (aaa.Substring(0, 1) == "0") { try { JavaScriptSerializer serializer = new JavaScriptSerializer(); // var obj = serializer.DeserializeObject(aaa);//反序列化 aaa=aaa.substring(2,aaa.length-2); ArrayList dic = serializer.Deserialize<ArrayList>(aaa);//反序列化ArrayList类型 if (dic.Count > 0) { foreach (Dictionary<string, object> drow in dic) { if (dtb.Columns.Count == 0) { foreach (string key in drow.Keys) { dtb.Columns.Add(key, drow[key].GetType());//添加dt的列名 } } DataRow row = dtb.NewRow(); foreach (string key in drow.Keys) { row[key] = drow[key];//添加列值 } dtb.Rows.Add(row);//添加一行 } } } catch (Exception e) { // } } else { // } return dtb; }
希望本文所述对大家C#程序设计的学习有所帮助。