天天看點

DataTable序列化成Json字元串

<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會存在安全性的問題。