Home > Backend Development > C++ > How Can I Efficiently Convert a C# DataTable to a Custom JSON Format?

How Can I Efficiently Convert a C# DataTable to a Custom JSON Format?

DDD
Release: 2025-01-21 16:43:09
Original
630 people have browsed it

How Can I Efficiently Convert a C# DataTable to a Custom JSON Format?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template