时间:2021-07-01 10:21:17 帮助过:17人阅读
本文实例讲述了asp.net使用DataTable构造Json字符串的方法。分享给大家供大家参考,具体如下:
/// <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程序设计有所帮助。