以下是将 DataTable 表格字段转换为 JSON 字符串的示例代码:

using System;
using System.Data;
using System.Web.Script.Serialization;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个 DataTable 对象
        DataTable dt = new DataTable();

        // 添加一些列
        dt.Columns.Add('ID', typeof(int));
        dt.Columns.Add('Name', typeof(string));
        dt.Columns.Add('Age', typeof(int));

        // 添加一些行
        dt.Rows.Add(1, 'Tom', 20);
        dt.Rows.Add(2, 'Jerry', 25);
        dt.Rows.Add(3, 'John', 30);

        // 转换为 JSON 字符串
        string json = DataTableToJson(dt);

        // 输出结果
        Console.WriteLine(json);
    }

    static string DataTableToJson(DataTable dt)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.MaxJsonLength = Int32.MaxValue;
        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);
    }
}

以上代码使用了 JavaScriptSerializer 类将 DataTable 表格字段转换为 JSON 字符串。首先,我们将 DataTable 转换为一个包含字典对象的列表。接着,我们使用 JavaScriptSerializer 类将列表序列化为 JSON 字符串。最后,我们输出结果。

C# DataTable 转 JSON 字符串:完整代码示例

原文地址: https://www.cveoy.top/t/topic/lMPE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录