DataTable序列化成Json字符串

来源:互联网 发布:逆袭网络剧第三集土豆 编辑:程序博客网 时间:2024/04/29 16:17
     <span style="white-space:pre"></span> /// <summary>        /// 将DataTable序列化为Json字符串        /// </summary>        /// <param name="table">要序列化的DataTable</param>        /// <returns>返回一个泛型List</returns>        public List<Dictionary<string, object>> DataTableToJson(DataTable table)        {             //实例化一个list泛型,使用Dictionary。            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();            foreach (DataRow dr in table.Rows)             {                Dictionary<string, object> dic = new Dictionary<string, object>();                //dictionary不允许有相同的KEY值,所以每次都需要实例化一个Dictionary                 foreach(DataColumn dc in table.Columns)                 {                     dic.Add(dc.ColumnName, dr[dc]); //将KEY和VALUE存到Dictionary中                 }                 list.Add(dic);//新的Dictionary添加到List中            }            return list;//返回一个list集合        }

 上面这个方法只是将DataTable每一行每一列的数据以key/value值存放在一个Dictionary中,这样才能序列化成一个JSON字符串。

这种方法不适用与操作大量的数据,因为每一行的每一列都是一个Dictionary,如果数据太多,内存会崩盘。

  public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/html";              DataTable table = SqlHelp.ExecutDataTable("select * from Table");            List<Dictionary<string, object>> toJson = DataTableToJson(table); //接收            JavaScriptSerializer json = new JavaScriptSerializer(); //转换            context.Response.Write(json.Serialize(toJson));   //返回给客户端        }   
在客户端用 JSON.Parse()方法转换为一个js对象,不是用evel(),evel会存在安全性的问题。

 

0 0
原创粉丝点击