How to Convert CSV to JSON in C# .NET Core Framework
Writing code to convert data from CSV to JSON can take time away from other pressing tasks. Thankfully, we don’t always have to write all that code ourselves.
Using ready-to-run code examples provided below, we can take advantage of a free API that converts our CSV files into JSON objects. Using an API makes this everyday conversion extremely quick and easy, and it offloads some of the processing burden from our server to an external server.
We can authorize our API call with a free API key, which will allow us to make up to 800 conversions per month with no commitments.
To structure our API call, let’s begin by installing the SDK. Let’s run the following command in our Package Manager console to install via NuGet:
Install-Package Cloudmersive.APIClient.NETCore.DocumentAndDataConvert -Version 2.2.1
Next, let’s copy the below code into our file to call the function. Let’s copy our free API key into the indicated snippet and provide our CSV file for a formData request:
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Model;
namespace Example
{
public class ConvertDataCsvToJsonExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new ConvertDataApi();
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input file to perform the operation on.
var columnNamesFromFirstRow = true; // bool? | Optional; If true, the first row will be used as the labels for the columns; if false, columns will be named Column0, Column1, etc. Default is true. Set to false if you are not using column headings, or have an irregular column structure. (optional)
try
{
// Convert CSV to JSON conversion
Object result = apiInstance.ConvertDataCsvToJson(inputFile, columnNamesFromFirstRow);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertDataApi.ConvertDataCsvToJson: " + e.Message );
}
}
}
}
Now we can easily convert CSV to JSON with minimal code.