本文转载:http://www.cnblogs.com/liang--liang/archive/2013/02/05/2893030.html
public static string DataTable2Json(System.Data.DataTable dt) { System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder(); jsonBuilder.Append("{"); jsonBuilder.AppendFormat("\"total\":{0}, ", dt.Rows.Count); jsonBuilder.Append("\"rows\":[ "); for (int i = 0; i < dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("\""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("\":\""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("\","); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); jsonBuilder.Append("}"); return jsonBuilder.ToString(); }
本文学习中使用的:
int pagNum = int.Parse(Request["page"].ToString()); int pageSize = int.Parse(Request["rows"].ToString()); string jsonStr = string.Empty; UserInfoDataContextDataContext dbContext = new UserInfoDataContextDataContext("server=.;database=NorthWind;uid=sa;pwd=123456"); var userInfoLst = dbContext.UserInfo.Take(pageSize * pagNum).Skip((pagNum - 1) * pageSize).Select(s => s); jsonStr = JsonHelper.ToJson(userInfoLst); System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder(); jsonBuilder.Append("{"); jsonBuilder.AppendFormat("\"total\":{0}, ", dbContext.UserInfo.Count()); jsonBuilder.Append("\"rows\":"); jsonBuilder.AppendFormat("{0}", jsonStr); jsonBuilder.Append("}"); return Content(jsonBuilder.ToString());
JsonHelp代码段:
/// <summary> /// Json数据转换封装 /// </summary> public static class JsonHelper { public static String ToJson(object obj) { return Newtonsoft.Json.JsonConvert.SerializeObject(obj); } }
注意返回的Json格式,否则会导致datagrid不会显示数据的。
时间: 2024-10-17 10:35:23