码迷,mamicode.com
首页 > 其他好文 > 详细

DataTable的序列化和反序列化

时间:2015-08-19 12:39:30      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

/// <summary>
/// DataTable序列化
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string SerializeDataTable(DataTable dt)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)//每一行信息,新建一个Dictionary<string,object>,将该行的每列信息加入到字典
{
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);//调用Serializer方法
}
/// <summary>
/// DataTable反序列化
/// </summary>
/// <param name="strJson"></param>
/// <returns></returns>
public static DataTable DeserializerTable(string strJson)
{
DataTable dt = new DataTable();
JavaScriptSerializer serializer = new JavaScriptSerializer();
ArrayList arralList = serializer.Deserialize<ArrayList>(strJson);//反序列化ArrayList类型
if (arralList.Count > 0)//反序列化后ArrayList个数不为0
{
foreach (Dictionary<string, object> row in arralList)
{
if (dt.Columns.Count == 0)//新建的DataTable中无任何信息,为其添加列名及类型
{
foreach (string key in row.Keys)
{
dt.Columns.Add(key, row[key].GetType());//添加dt的列名
}
}
DataRow dr = dt.NewRow();
foreach (string key in row.Keys)//讲arrayList中的值添加到DataTable中
{

dr[key] = row[key];//添加列值
}
dt.Rows.Add(dr);//添加一行
}
}
return dt;
}

DataTable的序列化和反序列化

标签:

原文地址:http://www.cnblogs.com/xsj1989/p/4741567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!