DataTable to json(DataTable 转换为json数据)

 1 public static string DataTableToJSON(DataTable table)
 2 {
 3     List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
 4 
 5     foreach (DataRow row in table.Rows)
 6     {
 7         Dictionary<string, object> dict = new Dictionary<string, object>();
 8 
 9         foreach (DataColumn col in table.Columns)
10         {
11             dict[col.ColumnName] = row[col];
12         }
13         list.Add(dict);
14     }
15     JavaScriptSerializer serializer = new JavaScriptSerializer();
16     return serializer.Serialize(list);
17 }

 (DataTable 转换为json数据)

 

ReadToJson
 1 public string ReadToJson(SqlDataReader reader)
 2 {
 3   List<string> cols = new List<string>(10);
 4   int ncols = reader.FieldCount;
 5   for (int i = 0; i < ncols; ++i)
 6   {
 7     cols.Add(reader.GetName(i));
 8   }
 9   StringBuilder sbJson = new StringBuilder("[");
10   //process each row
11   while (reader.Read())
12   {
13     sbJson.Append("{");
14     foreach (string col in cols)
15     {
16       sbJson.AppendFormat("\"{0}\":{1}, ", col, reader[col]);
17     }
18     sbJson.Replace(", ", "},", sbJson.Length - 2, 2);
19   }
20   sbJson.Replace("},", "}]", sbJson.Length - 2, 2);
21   return sbJson.ToString();
22 }

 

posted @ 2013-01-16 17:37  ミ茹此茹此↘  Views(282)  Comments(0Edit  收藏  举报