创建一个DataTable对象:
1 DataTable dt = new DataTable(); 2 DataColumn dcName = new DataColumn("Name"); 3 DataColumn dcAge = new DataColumn("Age"); 4 DataColumn dcCity = new DataColumn("City"); 5 6 dt.Columns.Add(dcName); 7 dt.Columns.Add(dcAge); 8 dt.Columns.Add(dcCity); 9 for (int i = 0; i < 10; i++) 10 { 11 DataRow dr = dt.NewRow(); 12 dr[0] = "Name" + i; 13 dr[1] = "Age" + i; 14 dr[2] = "City" + i; 15 dt.Rows.Add(dr); 16 }
转换为json格式:
1 string json = JsonConvert.SerializeObject(dt); 2 Console.WriteLine(json);
json格式转换为DataTable:
1 DataTable dt1 = JsonConvert.DeserializeObject<DataTable>(json); 2 for (int i = 0; i < dt1.Rows.Count; i++) 3 { 4 DataRow dr = dt1.Rows[i]; 5 Console.WriteLine("{0}\t{1}\t{2}\t", dr[0], dr[1], dr[2]); 6 }