.net DataTable序列化成Json

时间:2022-02-19 00:24:26

/// <summary>
/// DataTable序列化
/// </summary>
/// <param name="dt"></param>
/// <param name="flag">false</param>
/// <returns></returns>
public string Serialize(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> result = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName.ToLower() == "checked")
{
result.Add(dc.ColumnName.ToLower(), dr[dc] == DBNull.Value || false ? false : true);
}
else
{
result.Add(dc.ColumnName.ToLower(), dr[dc].ToString().ToLower());
}
}
list.Add(result);
}
return serializer.Serialize(list); ;
}