public static DataTable JsonToDataTable(string json) { DataTable dt = null; dt = new DataTable();//实例化 JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json); if (arrayList.Count > 0) { foreach (Dictionary<string, object> dictionary in arrayList) { if (dictionary.Keys.Count<string>() == 0) { return dt; } foreach (string current in dictionary.Keys) { dt.Columns.Add(current, dictionary[current].GetType()); } DataRow dataRow = dt.NewRow(); foreach (string current in dictionary.Keys) { dataRow[current] = dictionary[current]; } dt.Rows.Add(dataRow); //循环添加行到DataTable中 } } return dt; }
Json To DataTable
public static string DataTableToJson(DataTable dt) { JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 ArrayList arrayList = new ArrayList(); foreach (DataRow dataRow in dt.Rows) { Dictionary<string, object> dictionary = new Dictionary<string, object>(); //实例化一个参数集合 foreach (DataColumn dataColumn in dt.Columns) { dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString()); } arrayList.Add(dictionary); //ArrayList集合中添加键值 } return javaScriptSerializer.Serialize(arrayList); //返回一个json字符串 }
DataTable To Json
时间: 2024-10-10 11:00:20