Convert CSV to JSON using Java

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:

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

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

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.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store