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); ;
}
//反序列化 www.zzzyk.com
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);//反序列化
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)
补充:Web开发 , ASP.Net ,