将DataTable转成Json字符串

 1 public string ToJson(DataTable tbl)
 2         {
 3             if (tbl.Rows.Count > 0)
 4             {
 5                 DataRowCollection rows = tbl.Rows;
 6                 StringBuilder sb = new StringBuilder();
 7                 sb.Append("[");
 8                 int rowcount = 0;
 9                 int columnCount = 0;
10                 foreach (DataRow row in tbl.Rows)
11                 {
12                     rowcount++;
13                     sb.Append("{");
14                     foreach (DataColumn column in tbl.Columns)
15                     {
16                         columnCount++;
17                         sb.AppendFormat("{0}:'{1}'{2}", column.ColumnName, row[column.ColumnName].ToString(), columnCount == tbl.Columns.Count ? "" : ",");
18                     }
19                     columnCount = 0;
20                     sb.Append("}");
21                     sb.AppendFormat("{0}", rowcount == tbl.Rows.Count ? "" : ",");
22                 }
23                 sb.Append("]");
24                 return sb.ToString();
25             }
26             else
27             {
28                 return "";
29             }
30         }

 

posted @ 2020-07-20 10:44  墨染暖栀  阅读(159)  评论(0编辑  收藏  举报
/* 看板娘 */ /* 粒子吸附*/