Convert CSV to JSON using Java

Cloudmersive
2 min readFeb 22, 2021

While Excel and CSV are the most familiar and widely used data-storing formats, they can become cumbersome if the file content is too extensive. Converting your CSV file to JSON can enable easier usage for online formats that may be employed by your business applications or website. Our CSV to JSON API can be performed on any CSV file with little to no hassle on your end.

To begin the operation, we will first install the Maven or Gradle SDK. For this example, I will be using Gradle, so I will add the following in the root.build.gradle at the end of the repositories:

allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}

Next, I’ll add the dependency in the build.gradle:

dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
}

Now to kick things into gear, I will add the imports, instance the API, and call the conversion function:

// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertDataApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
ConvertDataApi apiInstance = new ConvertDataApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Boolean columnNamesFromFirstRow = true; // Boolean | 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.
try {
Object result = apiInstance.convertDataCsvToJson(inputFile, columnNamesFromFirstRow);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertDataApi#convertDataCsvToJson");
e.printStackTrace();
}

The response that is returned will present your new JSON data for use. Head to the Cloudmersive website to retrieve your free API key and explore our conversion APIs, as well as the multitude of other APIs available.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.