I am pretty new at C# and .NET, but I\'ve made this code to call a stored procedure, and I then want to take the returned DataTable and convert it to JSON.
Although the JavaScriptSerializer (System.Web.Script.Serialization.JavaScriptSerializer) cannot convert a DataTable directly into JSON, it is possible to unpack a DataTable into a List that may then be serialized.
The following function converts an arbitrary DataTable into a JSON string (without prior knowledge about field names or data types):
public static string DataTableToJSON(DataTable table)
{
var list = new List>();
foreach (DataRow row in table.Rows)
{
var dict = new Dictionary();
foreach (DataColumn col in table.Columns)
{
dict[col.ColumnName] = row[col];
}
list.Add(dict);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}