JSON string to CSV and CSV to JSON conversion in c#
<p>I'm working with JSON/CSV files in my asp.net web API project and tried with <a href="https://github.com/JoshClose/CsvHelper" rel="noreferrer">CSVHelper</a> and <a href="https://github.com/ServiceStack/ServiceStack.Text" rel="noreferrer">ServiceStack.Text</a> libraries but couldn't make it work.</p>

<p>The JSON file containing an array is dynamic and may have any number of fields</p>

<p>I read the file using streamreader and then need to convert it into CSV file to make it downloadable for end users.</p>

<p><strong>example file text</strong></p>

<pre><code>[{"COLUMN1":"a","COLUMN2":"b","COLUMN3":"c","COLUMN4":"d","COLUMN5":"e"},
 {"COLUMN1":"a","COLUMN2":"b","COLUMN3":"c","COLUMN4":"d","COLUMN5":"e"}]
</code></pre>

<p><strong>JSON to CSV</strong></p>

<pre><code>public static string jsonStringToCSV(string content)
{
    var jsonContent = (JArray)JsonConvert.DeserializeObject(content);

    var csv = ServiceStack.Text.CsvSerializer.SerializeToCsv(jsonContent);
    return csv;
}
</code></pre>

<p>This doesn't result me CSV data</p>

<p><a href="https://i.stack.imgur.com/lPTMM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lPTMM.png" alt="enter image description here"></a></p>

<p>Then some files are delimiter type with comma or tab and and i want to utilize <a href="https://github.com/JoshClose/CsvHelper" rel="noreferrer">CSVHelper</a> to convert CSV string to IEnumerable dynamically</p>

<pre><code>public static IEnumerable StringToList(string data, string delimiter, bool HasHeader)
{
    using (var csv = new CsvReader(new StringReader(data)))
    {
         csv.Configuration.SkipEmptyRecords = true;
         csv.Configuration.HasHeaderRecord = HasHeader;
         csv.Configuration.Delimiter = delimiter;

         var records = csv.GetRecords();
         return records;
     }
}
</code></pre>