C#中datatable序列化與反序列化實例剖析。本站提示廣大學習愛好者:(C#中datatable序列化與反序列化實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中datatable序列化與反序列化實例剖析正文
本文實例講述了C#中datatable序列化與反序列化,分享給年夜家供年夜家參考。詳細辦法以下:
1、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); ; }
2、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#法式設計的進修有所贊助。