DataTable转Json Json转DataTable
/// <summary>
/// DataTable转Json
/// </summary>
/// <param name="dtb"></param>
/// <returns></returns>
#region DataTable转Json
private string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
#endregion
/// <summary>
/// Json转DataTable
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
#region Json转DataTable
private DataTable Json2Dtb(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = jss.Deserialize<ArrayList>(json);
DataTable dtb = new DataTable();
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());
}
} DataRow row = dtb.NewRow();
foreach (string key in drow.Keys)
{ row[key] = drow[key]; }
dtb.Rows.Add(row);
}
}
return dtb;
}
原文地址:https://www.cnblogs.com/jiazuzhuzhu/p/8434318.html