01 public class JsonUtil
02 {
03 public string ToJson(DataSet dataSet)
04 {
05 string jsonString = "{";
06 foreach (DataTable table in dataSet.Tables)
07 {
08 jsonString += """" + table.TableName + """:" + ToJson(table) + ",";
09 }
10 jsonString = jsonString.TrimEnd(',');
11 return jsonString + "}";
12 }
13 public string ToJson(DataTable dt)
14 {
15 StringBuilder jsonString = new StringBuilder();
16 jsonString.Append("[");
17 DataRowCollection drc = dt.Rows;
18 for (int i = 0; i < drc.Count; i++)
19 {
20 jsonString.Append("{");
21 for (int j = 0; j < dt.Columns.Count; j++)
22 {
23 string strKey = dt.Columns[j].ColumnName;
24 string strValue = drc[i][j].ToString();
25
26 Type type = dt.Columns[j].DataType;
27 jsonString.Append("""" + strKey + """:");
28 strValue = String.Format(strValue, type);
29
30 jsonString.Append("""" + strValue + """,");
31
32 }
33 jsonString.Append("},");
34 }
35 jsonString.Remove(jsonString.Length - 1, 1);
36 jsonString.Append("]");
37 return jsonString.ToString();
38 }
39 }
使用
1 JsonUtil ju = new JsonUtil();
2 Response.Write(ju.ToJson(ds));
更多信息请查看IT技术专栏