用法:上述方法是DataTable的扩展方法:静态类静态方法,变量前用this
(一)ps:普通datatable转标准json
DataTable dt = 获取db中的datatable数据。 string jsonStr = dt.DtToJson();//即可转标准json
(二)ps:普通datatable转标准json:使用与easyui分页标准
DataTable dt = TestManager.getData("CartLotteryCartPrizeSon", "Id", page, rows, whereStr, "", out totalRows, out totalPages);//通过分页存储过程获取的DataTable(返回总行数和总页数供easyui分页用) string jsonStr = dt.DtToJson(totalRows);//即可得到easyui标准的可分页的数据,直接供easyui用
private static readonly System.Web.Script.Serialization.JavaScriptSerializer Serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); /// <summary> /// DataTabel转标准json(兼用easyui的json标准) /// </summary> /// <param name="dt">DataTable数据源</param> /// <param name="total">可选:转普通json传>0的值或忽略此参数;如果针对easyui的json一定要把total参数分页的总行数传进来</param> /// <returns>标准json</returns> public static string DtToJson(this DataTable dt, int total) { Serializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 System.Collections.ArrayList arrayList = new System.Collections.ArrayList(); foreach (DataRow dataRow in dt.Rows) { try { 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集合中添加键值 } catch (Exception ex) { } } if (total > 0)//easyUI专用,分页的总行数 { var dictionary = new Dictionary<string, object>(); dictionary.Add("total", total);//此参数是easyUI专用 dictionary.Add("rows", arrayList);//此参数是easyUI专用 return Serializer.Serialize(dictionary); } else { return Serializer.Serialize(arrayList); } //返回一个json字符串 }
时间: 2024-10-03 14:45:15