In the previous article, I mentioned Get First Character or Nth Character of string in C# but in this article, I have mentioned how we can convert JSON to CSV in C# with a console application example.
JSON to CSV in C# using Custom Method
In this method, once we have created the console application, we will have to install below 2 NuGet packages
- Newtonsoft.JSON
- CsvHelper
You can install using "Tools" -> Nuget package manager -> Manage Nuget package for solution.
Once we are done with it.
using CsvHelper; // install CSV helper
using Newtonsoft.Json; // install Newtonsoft.JSON NuGet Package
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
namespace JSONToCSV
{
internal class Program
{
public static void Main()
{
var json = @"[{""Sample"":""StringValue"", ""Id"": 1},{""Sample"":""StringValue2"", ""Id"": 2}]";
JsonToCsv(json);
}
public static string JsonToCsv(string jsonContent)
{
var expandos = JsonConvert.DeserializeObject<ExpandoObject[]>(jsonContent);
using (TextWriter writer = new StreamWriter(@"D:\sample.csv"))
{
using (var csv = new CsvWriter(writer,System.Globalization.CultureInfo.CurrentCulture))
{
csv.WriteRecords((expandos as IEnumerable<dynamic>));
}
return writer.ToString();
}
}
}
}
Output:
As you can see in the above code, we were able to convert JSON into sample.csv as output.
JSON to CSV using Nuget Package
We have open source NuGet Package named Cinchoo ETL, which you can install in your .NET application and then convert JSON to CSV in C#.
Cinchoo ETL is a code-based ETL framework for extracting data from multiple sources, transforming, and loading into your very own data warehouse in .NET environment. You can have data in your data warehouse in no time.
For .NET framework, you can use below command to install it
Install-Package ChoETL.JSON
and for .NET Core
Install-Package ChoETL.JSON.NETStandard
Once, you are done installing the above NuGet Package, you can use the below C# code to convert JSON into CSV
using System;
using ChoETL;
public class Program
{
public static void Main()
{
using (var r = ChoJSONReader.LoadText(json))
{
using (var w = new ChoCSVWriter(Console.Out)
.WithFirstLineHeader()
)
w.Write(r);
}
}
static string json = @"[{""Sample"":""StringValue"", ""Id"": 1},{""Sample"":""StringValue2"", ""Id"": 2}]";
}
Which will give output as
Sample,Id
StringValue,1
StringValue2,2
Using above NuGet Package we can also use POCO objects to load JSON and then convert it into CSV.
That's it, hope it helps.
You may also like to read:
Convert CSV to JSON using Javascript
Parse CSV file data into Array Using Javascript