C# 将datatable 转换json

时间:2024-01-10 14:14:20
        public static string DataTableToJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{\"");
//jsonBuilder.Append(dt.TableName);
jsonBuilder.Append("data");
jsonBuilder.Append("\":[");
for (int i = ; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = ; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - , );
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - , );
jsonBuilder.Append("]}");
return jsonBuilder.ToString();
}