How to Convert a CSV File to a JSON Object Array with Java

Cloudmersive
2 min readJul 6, 2022

There are lots of reasons why you might be converting CSV files to JSON. For one thing, JSON objects are considerably more versatile in their usage, and for another, they support much greater scalability.

To make that conversion easily with a cloud service, take advantage of our CSV to JSON API. You can utilize this API for free by structuring your API call with the ready-to-run code examples we’ve provided below, and by registering a free account on our website to get your Cloudmersive API key.

Let’s begin by installing the Java SDK with Maven. Add a reference to the pom.xml repository:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

Then add one to the dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

That concludes installation; now you can include the import classes and call the API. Your only two required parameters include your input file & your API key, but you can optionally set a boolean to ‘false’ for ‘columnNamesFromFirstRow’ if you are NOT using column headings (or have an irregular column structure).

// 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();
}

--

--

Cloudmersive

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