public string ToJson(DataTable dt)
{
List<Dictionary<string, object>> dic = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
drow.Add(dc.ColumnName.ToLower(), dr[dc.ColumnName]);
}
dic.Add(drow);
}
//序列化
return Utilities.Helper.JsonHelper.Serialize(dic);
}
public DataTable ToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
List<Dictionary<string, object>> arrayList = Utilities.Helper.JsonHelper.Deserialize<List<Dictionary<string, object>>>(json);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == 0)
{
result = dataTable;
return result;
}
//Columns
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
//Rows
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
result = dataTable;
return result;
}
C# Json and DataTable 互转
于 2023-06-21 08:47:29 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)