Convert DataTable to JSON in C#
This article explores how to convert DataTable objects in C# to JSON format. The problem starts with retrieving records from the database into a DataTable, then converting it to a JSON object and returning it to a JavaScript function. However, the required JSON format is different from the current output. This article provides a solution to achieve the desired JSON format.
To solve this problem, you can use different serialization methods. Instead of using JsonConvert.SerializeObject
, consider using System.Web.Script.Serialization
in the JavaScriptSerializer
namespace. This alternative allows greater control over the JSON output structure.
Here is an example of how to implement this solution:
<code class="language-csharp">public string ConvertDataTabletoString() { DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection("YOUR_CONNECTION_STRING")) { using (SqlCommand cmd = new SqlCommand("YOUR_QUERY", con)) { con.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); Dictionary<string, object> row; foreach (DataRow dr in dt.Rows) { row = new Dictionary<string, object>(); foreach (DataColumn col in dt.Columns) { row.Add(col.ColumnName, dr[col]); } rows.Add(row); } return serializer.Serialize(rows); } } }</code>
The above is the detailed content of How Can I Efficiently Convert a C# DataTable to a Custom JSON Format?. For more information, please follow other related articles on the PHP Chinese website!