本文實例講述了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程序設計有所幫助。