1
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Collections; using System.Web.Script.Serialization; /// <summary> ///JsonHelper 的摘要说明 /// </summary> public class JsonHelper { public JsonHelper() { // //TODO: 在此处添加构造函数逻辑 // } #region Json 与 DataTable 的相互转换 /// <summary> /// Json 字符串转换为DataTable数据集合 /// </summary> /// <param name="strJson">待转换的Json字符串</param> /// <returns>返回DataTable集合</returns> public static DataTable JsonToDataTable(string strJson) { DataTable dt = new DataTable(); //实例化 JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(strJson); if (arrayList.Count > 0) { foreach (Dictionary<string, object> dic in arrayList) { if (dic.Keys.Count<string>() == 0) { return dt; } if (dt.Columns.Count == 0) { foreach (string key in dic.Keys) { dt.Columns.Add(key, dic[key].GetType()); } } DataRow dataRow = dt.NewRow(); foreach (string key in dic.Keys) { dataRow[key] = dic[key]; } dt.Rows.Add(dataRow); //循环添加行到DataTable中 } } return dt; } /// <summary> /// DataTable 对象 转换为Json 字符串 /// </summary> /// <param name="dt">带转换的DataTable数据集合</param> /// <returns>返回Json字符串</returns> 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> dic = new Dictionary<string, object>(); //实例化一个参数集合 foreach (DataColumn dataColumn in dt.Columns) { dic.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString()); } arrayList.Add(dic); //ArrayList集合中添加键值 } return javaScriptSerializer.Serialize(arrayList); //返回一个json字符串 } #endregion Json 与 DataTable 的相互转换 }
2