DataTable转换为Json字符串的三种方法

//第一种:使用StringBuilder 
 1 public string DataTableToJson(DataTable table)  
 2     {  
 3         var JsonString = new StringBuilder();  
 4         if (table.Rows.Count > 0)  
 5         {  
 6             JsonString.Append("[");  
 7             for (int i = 0; i < table.Rows.Count; i++)  
 8             {  
 9                 JsonString.Append("{");  
10                 for (int j = 0; j < table.Columns.Count; j++)  
11                 {  
12                     if (j < table.Columns.Count - 1)  
13                     {  
14                         JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");  
15                     }  
16                     else if (j == table.Columns.Count - 1)  
17                     {  
18                         JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");  
19                     }  
20                 }  
21                 if (i == table.Rows.Count - 1)  
22                 {  
23                     JsonString.Append("}");  
24                 }  
25                 else  
26                 {  
27                     JsonString.Append("},");  
28                 }  
29             }  
30             JsonString.Append("]");  
31         }  
32         return JsonString.ToString();    
33     }  
View Code

//第二种:使用JavaScriptSerializer序列化数据

 1 using System.Web.Script.Serialization;  
 2 
 3 public string DataTableToJsonWithJavaScriptSerializer(DataTable table)  
 4    {   
 5        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();   
 6        List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> ();   
 7        Dictionary < string, object > childRow;   
 8        foreach(DataRow row in table.Rows)  
 9        {   
10            childRow = new Dictionary < string, object > ();   
11            foreach(DataColumn col in table.Columns)  
12            {   
13                childRow.Add(col.ColumnName, row[col]);   
14            }   
15            parentRow.Add(childRow);   
16        }   
17        return jsSerializer.Serialize(parentRow);   
18    }    
View Code

 //第三种:使用Json.Net DLL (Newtonsoft)。

      这个方法中要添加Json.Net DLL引用,我们可以从Newtonsoft下载Json.Net DLL,再导入命名空间,代码如下:

  

1 using Newtonsoft.Json;  
2    
3 public string DataTableToJsonWithJsonNet(DataTable table)  
4    {   
5     string JsonString=string.Empty;   
6     JsonString = JsonConvert.SerializeObject(table);   
7     return JsonString;   
8    }  

 

posted @ 2016-12-07 16:14  稻草也疯狂  阅读(4304)  评论(0编辑  收藏  举报