C# DataTable to JSON Conversion: Achieving the Desired Format
This guide demonstrates how to convert a C# DataTable into a JSON string with a specific structure, avoiding the default JSON object format. The target format is a JSON object containing a "records" array of individual record objects.
Steps:
Populate the DataTable: Begin by creating a DataTable and populating it with data from your database (or any other source).
Use JavaScriptSerializer: Utilize the JavaScriptSerializer
class to handle the JSON serialization.
Create a List of Dictionaries: Construct a list to store each row of the DataTable as a dictionary.
Iterate and Populate Dictionaries: Loop through each DataRow
in the DataTable. For each row:
DataColumn
in the DataTable.col.ColumnName
) as the key and the corresponding column value (dr[col]
) as the value to the dictionary.Serialize the List: Finally, serialize the list of dictionaries using JavaScriptSerializer
, wrapping it in a JSON object with a "records" property.
Code Example:
<code class="language-csharp">using System.Web.Script.Serialization; using System.Data; using System.Collections.Generic; public string ConvertDataTableToJson() { DataTable dataTable = new DataTable(); // Fill dataTable with data from your database JavaScriptSerializer serializer = new JavaScriptSerializer(); List<Dictionary<string, object>> records = new List<Dictionary<string, object>>(); foreach (DataRow row in dataTable.Rows) { Dictionary<string, object> record = new Dictionary<string, object>(); foreach (DataColumn column in dataTable.Columns) { record.Add(column.ColumnName, row[column]); } records.Add(record); } return serializer.Serialize(new { records = records }); }</code>
This revised code provides a clear and efficient method for converting a DataTable to the specified JSON format, ensuring each record is properly represented within a "records" array. Remember to add the necessary using
statements.
The above is the detailed content of How to Convert a DataTable to a JSON String with a 'records' Array in C#?. For more information, please follow other related articles on the PHP Chinese website!