59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using SQLVision.Core.Models;
|
|
using System.Data;
|
|
using System.Text.Json;
|
|
|
|
namespace SQLVision.Services.Exporters;
|
|
|
|
public class JsonExporter : IExportHandler
|
|
{
|
|
private readonly ILogger<JsonExporter> _logger;
|
|
private readonly JsonSerializerOptions _jsonOptions;
|
|
|
|
public string FormatName => "JSON";
|
|
|
|
public JsonExporter(ILogger<JsonExporter> logger)
|
|
{
|
|
_logger = logger;
|
|
_jsonOptions = new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
};
|
|
}
|
|
|
|
public async Task ExportAsync(DataTable data, string filePath, ExportOptions options)
|
|
{
|
|
var records = ConvertDataTableToList(data);
|
|
var json = JsonSerializer.Serialize(records, _jsonOptions);
|
|
await File.WriteAllTextAsync(filePath, json);
|
|
|
|
_logger.LogInformation("Exported {Rows} rows to JSON: {FilePath}", data.Rows.Count, filePath);
|
|
}
|
|
|
|
public async Task<byte[]> ExportToMemoryAsync(DataTable data, ExportOptions options)
|
|
{
|
|
var records = ConvertDataTableToList(data);
|
|
var json = JsonSerializer.Serialize(records, _jsonOptions);
|
|
return System.Text.Encoding.UTF8.GetBytes(json);
|
|
}
|
|
|
|
private List<Dictionary<string, object>> ConvertDataTableToList(DataTable data)
|
|
{
|
|
var list = new List<Dictionary<string, object>>();
|
|
|
|
foreach (DataRow row in data.Rows)
|
|
{
|
|
var dict = new Dictionary<string, object>();
|
|
|
|
foreach (DataColumn column in data.Columns)
|
|
{
|
|
dict[column.ColumnName] = row[column] ?? DBNull.Value;
|
|
}
|
|
|
|
list.Add(dict);
|
|
}
|
|
|
|
return list;
|
|
}
|
|
} |