How to convert a DataSet to JSON for return via ajax

0 comments

Here is some code:

		public static string DumpTableToJSON(DataTable dt) {
			string result = "\n";
			for (int rowIndex = 0; rowIndex < 10 && rowIndex < dt.Rows.Count; rowIndex++) {
				var row = dt.Rows[rowIndex];
				int numcols = row.Table.Columns.Count;
				if (rowIndex == 0) {
					//header
					result += "\"header\":[";
					for (int sc = 0; sc < numcols; sc++) {
						if (sc > 0) result += ", ";
						string name = row.Table.Columns[sc].ColumnName;
						result += "\"" + name + "\"";
					}
					result += "]";
				}
				if (rowIndex == 0) result += ",\"rows\":[[";
				if (rowIndex > 0) result += ",[";
				for (int sc = 0; sc < numcols; sc++) {
					if (sc > 0) result += ", ";
					//string name = row.Table.Columns[sc].ColumnName;
					result += "\"" + row[sc].ToString().Trim().Replace("\"", "\"\"") + "\"";
				}
				result += "]";
			}
			result += "]";
			result = "{\"data\":{" + result + "}}";
			//dout(result);
			//Response.Write(result);
			return result;
		}

Comments


Leave a Comment