DataTable序列化


DataTable是復雜對象,無法直接序列化,必須通過其他的方式來實現

下面介紹一下常用的幾種方式

1、先轉換為List,再序列化List

下面是DataTable轉換為List的方法

 1         protected  List<T> ConvertToList<T>(DataTable dt) where T : new()
 2         {
 3             // 定義集合    
 4             List<T> ts = new List<T>();
 5 
 6             // 獲得此模型的類型   
 7             Type type = typeof(T);
 8             string tempName = "";
 9 
10             foreach (DataRow dr in dt.Rows)
11             {
12                 T t = new T();
13                 // 獲得此模型的公共屬性      
14                 PropertyInfo[] propertys = t.GetType().GetProperties();
15                 foreach (PropertyInfo pi in propertys)
16                 {
17                     tempName = pi.Name;  // 檢查DataTable是否包含此列    
18 
19                     if (dt.Columns.Contains(tempName))
20                     {
21                         // 判斷此屬性是否有Setter      
22                         if (!pi.CanWrite) continue;
23 
24                         object value = dr[tempName];
25                         if (value != DBNull.Value)
26                             pi.SetValue(t, value, null);
27                     }
28                 }
29                 ts.Add(t);
30             }
31             return ts;
32         } 

然后使用JavaScriptSerializer類實現序列化

1    List<User> lstUer = ConvertToList<User>(dtUser);
2    JavaScriptSerializer jss = new JavaScriptSerializer();
3    string json = jss.Serialize(lstUer);

轉換為List在序列化有一個缺點,就是必須建立DataTable對應的實體類

2、使用Newtonsoft.Json實現

string json = JsonConvert.SerializeObject(table); 

這種方法必須引入第三方類庫Newtonsoft.Json.dll

3、直接遍歷拼接JSON字符串實現

 1  protected  string DataTable2JsonString(DataTable dt)
 2  {
 3       if (dt == null || dt.Rows.Count < 1)
 4       {
 5            return "[]";
 6       }
 7       string strjson = "[";
 8       for (int i = 0; i < dt.Rows.Count; i++)
 9       {
10            strjson += dt.Rows[i].ToJSON() + ",";
11       }
12       strjson = strjson.TrimEnd(',');
13       strjson += "]";
14       return strjson;
15  } 

4、使用擴展方法

遍歷DataTable歷生成JSON字符串的方法,在DataTable結果集十分龐大的時候,耗費的實際非常長

曾經做了一個測試,一個SQL語句查詢的結果有28000條,查詢本身花費5秒時間,但序列化的字符串返回前台卻需要一分鍾甚至更長

可以使用下面的方法,必須為靜態類和靜態方法

 1 public static class Common
 2 {
 3 
 4     public static string DataTableToJson(DataTable dt)
 5     {
 6         List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
 7         foreach (DataRow dr in dt.Rows)
 8         {
 9             Dictionary<string, object> result = new Dictionary<string, object>();
10             foreach (DataColumn dc in dt.Columns)
11             {
12                 result.Add(dc.ColumnName, dr[dc]);
13             }
14             list.Add(result);
15         }
16 
17         return SerializeToJson(list,100);
18     }
19     public static string SerializeToJson(this object obj, int recursionLimit)
20     {
21         JavaScriptSerializer serialize = new JavaScriptSerializer();
22         serialize.RecursionLimit = recursionLimit;
23         serialize.MaxJsonLength = Int32.MaxValue; 
24         return serialize.Serialize(obj);
25     }
26 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM