This code reads a JSON file named “data.json” using C# and converts it into a DataTable using the Newtonsoft.Json library from NuGet packages. Then it calls the DataTableToCsv() method which takes the DataTable as an argument and returns a string in CSV format. The returned string is then written to a file named “data.csv” using the File.WriteAllText() method.
using System;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
class Program
{
static void Main()
{
// Read the JSON file into a string
string json = File.ReadAllText("data.json");
// Convert the JSON string to a JObject
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
// Convert the JObject to a DataTable
DataTable table = JsonToDataTable(obj);
// Convert the DataTable to a CSV string
string csv = DataTableToCsv(table);
// Write the CSV string to a file
File.WriteAllText("data.csv", csv);
}
static DataTable JsonToDataTable(JObject json)
{
DataTable table = new DataTable();
// Get the array of JSON objects
JArray jsonArray = (JArray)json["data"];
// Get the column names from the first object
JObject firstObject = (JObject)jsonArray.First;
foreach (JProperty prop in firstObject.Properties())
table.Columns.Add(prop.Name);
// Add the data rows
foreach (JObject obj in jsonArray)
{
DataRow row = table.NewRow();
foreach (DataColumn column in table.Columns)
row[column.ColumnName] = obj[column.ColumnName].ToString();
table.Rows.Add(row);
}
return table;
}
static string DataTableToCsv(DataTable table)
{
StringBuilder sb = new StringBuilder();
// Get the column names
string[] columnNames = table.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
// Loop through the rows and get the data
foreach (DataRow row in table.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}
return sb.ToString();
}
}
