以下是将 C# DataTable 转换为 JSON 字符串的示例代码:

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

// 将DataTable转换为JSON字符串
public static string DataTableToJson(DataTable table)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    foreach (DataRow row in table.Rows)
    {
        Dictionary<string, object> dict = new Dictionary<string, object>();
        foreach (DataColumn col in table.Columns)
        {
            dict[col.ColumnName] = row[col];
        }
        rows.Add(dict);
    }
    return serializer.Serialize(rows);
}

使用示例:

DataTable table = new DataTable();
table.Columns.Add("id", typeof(int));
table.Columns.Add("name", typeof(string));
table.Rows.Add(1, "Alice");
table.Rows.Add(2, "Bob");
string json = DataTableToJson(table);
Console.WriteLine(json);
// 输出:[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]

注意:在上面的示例中,我们使用了JavaScriptSerializer类将DataTable转换为JSON字符串。但是,这个类已经过时了,官方推荐使用System.Text.JsonNewtonsoft.Json库来进行JSON序列化。如果你使用的是.NET Core 3.0及以上版本,可以使用System.Text.Json库来替代上面的代码。

C# DataTable 转 JSON 字符串:方法详解及示例

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

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