本文实例讲述了asp.net使用DataTable构造Json字符串的方法。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
/// <summary> /// 将datatable转换为json /// </summary> /// <param name="dtb"></param> /// <returns></returns> private string Dtb2Json(DataTable dtb) { JavaScriptSerializer jss = new JavaScriptSerializer(); System.Collections.ArrayList dic = new System.Collections.ArrayList(); foreach (DataRow dr in dtb.Rows) { System.Collections.Generic.Dictionary< string , object > drow = new System.Collections.Generic.Dictionary< string , object >(); foreach (DataColumn dc in dtb.Columns) { drow.Add(dc.ColumnName, dr[dc.ColumnName]); } dic.Add(drow); } //序列化 return jss.Serialize(dic); } /// <summary> /// 构建JSON字符串 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string CreateJsonParameters(DataTable dt) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (dt != null && dt.Rows.Count > 0) { sb.Append( "[" ); for ( int i = 0; i < dt.Rows.Count; i++) { sb.Append( "{" ); for ( int j = 0; j < dt.Columns.Count; j++) { //如果值不是最后一个则添加逗号分隔 if (j < dt.Columns.Count - 1) { sb.Append( "/" " + dt.Columns[j].ColumnName.ToString() + " / ":" + "/" " + dt.Rows[i][j].ToString() + " / "," ); } //如果值为最后个字符则不添加逗号 else if (j == dt.Columns.Count - 1) { sb.Append( "/" " + dt.Columns[j].ColumnName.ToString() + " / ":" + "/" " + dt.Rows[i][j].ToString() + " / "" ); } } //如果为最后一个值的话 则不添加逗号 if (i == dt.Rows.Count - 1) { sb.Append( "}" ); } else { sb.Append( "}," ); } } sb.Append( "]" ); return sb.ToString(); } else { return null ; } } |
希望本文所述对大家asp.net程序设计有所帮助。