DataTable转Json Json转DataTable
DataTable转Json Json转DataTable,有需要的朋友可以参考下。
DataTable转Json Json转DataTable
///<summary>
///DataTable转Json
///</summary>
///<paramname="dtb"></param>
///<returns></returns>
#regionDataTable转Json
privatestringDtb2Json(DataTabledtb)
{
JavaScriptSerializerjss=newJavaScriptSerializer();
ArrayListdic=newArrayList();
foreach(DataRowrowindtb.Rows)
{
Dictionary<string,object>drow=newDictionary<string,object>();
foreach(DataColumncolindtb.Columns)
{
drow.Add(col.ColumnName,row[col.ColumnName]);
}
dic.Add(drow);
}
returnjss.Serialize(dic);
}
#endregion
///<summary>
///Json转DataTable
///</summary>
///<paramname="json"></param>
///<returns></returns>
#regionJson转DataTable
privateDataTableJson2Dtb(stringjson)
{
JavaScriptSerializerjss=newJavaScriptSerializer();
ArrayListdic=jss.Deserialize<ArrayList>(json);
DataTabledtb=newDataTable();
if(dic.Count>0)
{
foreach(Dictionary<string,object>drowindic)
{
if(dtb.Columns.Count==0)
{
foreach(stringkeyindrow.Keys)
{
dtb.Columns.Add(key,drow[key].GetType());
}
}DataRowrow=dtb.NewRow();
foreach(stringkeyindrow.Keys)
{row[key]=drow[key];}
dtb.Rows.Add(row);
}
}
returndtb;
}