using System.Text;
using System.Collections.Generic;
1)dataTable转Json(表格有名称:dt.TableName)
public static string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{\""); jsonBuilder.Append(dt.TableName); jsonBuilder.Append("\":["); //jsonBuilder.Append("["); 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(); }
JS取值
var txt = eval("("+window.event.returnValue+")");
var value1 = txt[tableName][0]["value1"];
var value2 = txt[tableName][0]["value2"];
2)DataSet转Json
public static string Dataset2Json(DataSet ds) { StringBuilder json = new StringBuilder(); foreach (DataTable dt in ds.Tables) { json.Append("{\""); json.Append(dt.TableName); json.Append("\":"); json.Append(DataTable2Json(dt)); json.Append("}"); } return json.ToString(); }
3)dataTable转Json(表格没有名称)
public static string DataTableToJson(DataTable dt) { StringBuilder Json = new StringBuilder(); Json.Append("["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{ "); for (int j = 0; j < dt.Columns.Count; j++) { Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + TextToHtml(dt.Rows[i][j].ToString()) + "\""); if (j < dt.Columns.Count - 1) { Json.Append(","); } } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("]"); return Json.ToString(); }
取值:
$.each(data, function (idx, obj) {
alert(obj.ClassName);
alert(obj['ClassName']); });