JSON字符串轉換ToDataTable

简易JSON字符串转换

 1 /// <summary>
 2 /// Json 字符串 To DataTable数据集合
 3 /// </summary>
 4 /// <param name="json"></param>
 5 /// <returns></returns>
 6 public static DataTable JSONToDataTable(string json)
 7 {
 8     DataTable dtResult = new DataTable();
 9     try
10     {
11         JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
12         javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
13         ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
14         if (arrayList.Count > 0)
15         {
16             foreach (Dictionary<string, object> dictionary in arrayList)
17             {
18                 if (dictionary.Keys.Count<string>() == 0)
19                 {
20                     return dtResult;
21                 }
22                 //Columns
23                 if (dtResult.Columns.Count == 0)
24                 {
25                     foreach (string current in dictionary.Keys)
26                     {
27                         dtResult.Columns.Add(current, dictionary[current].GetType());
28                     }
29                 }
30                 //Rows
31                 DataRow dataRow = dtResult.NewRow();
32                 foreach (string current in dictionary.Keys)
33                 {
34                     dataRow[current] = dictionary[current];
35                 }
36                 dtResult.Rows.Add(dataRow);
37             }
38         }
39     }
40     catch (Exception e)
41     {
42         throw e;
43     }
44     return dtResult;
45 }
View Code

 

posted @ 2020-05-21 15:46  Yookee  阅读(140)  评论(0编辑  收藏  举报