Here we’ll convert CSV File to JSON Format in Java using the CsvMapper class and Jackson so that you can read and write CSV files as well as convert them to JSON format, which will come in handy if you want to perform further manipulations with your dataset.
TIP: CsvMapper class is specialized ObjectMapper. Jackson is a very popular and efficient java based library to serialize or map java objects to JSON and vice versa.
Methods to Convert CSV File to JSON Format in Java
Convert using CsvMapper Class
We can use the reader() method for constructing ObjectReader with default settings. In order to convert this, we need to import the com.fasterxml.jackson.dataformat.csv package.
Example
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.dataformat.csv.*;
public class CsvToJsonTest {
public static void main(String args[]) throws Exception {
File input = new File("input.csv");
try {
CsvSchema csv = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader().forType(Map.class).with(csv).readValues(input);
List<Map<?, ?>> list = mappingIterator.readAll();
System.out.println(list);
} catch(Exception e) {
e.printStackTrace();
Output
[{last name=Chandra, first name=Ravi, location=Bangalore}]
}
}
}
Convert using the Jackson
We can convert CSV Files to JSON Format via a POJO using Jackson. In this approach, we define POJOs and use a simple string split to convert CSV data into POJOs, which are serialized to JSON.
Simple CSV Parsing
If the CSV file is simple or without quoted fields or commas, then you can split the CSV fields with the use of a simple pattern matcher.
Pattern pattern = Pattern.compile(“,”);
Defines POJO
Whenever we parse the CSV data, POJO creates Plain-Old-Java-Object.
public class Player {
private int year;
private String teamId;
private String leagueId;
private String playerId;
private int salary;
public Player(int year, String teamId, String leagueId, String playerId, int salary) {
this.year = year;
this.teamId = teamId;
this.leagueId = leagueId;
this.playerId = playerId;
this.salary = salary;
}
// getters and setters here
};
Reading the CSV Data
Open the CSV file using a BufferedReader in a try-with-resources block.
try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) {
// processing code here
}
Create the List of POJOs using a streaming pipeline. Skip the first line because it is the CSV header. Split the line into fields, converted it to appropriate types, and create the object using a pattern.
List<Player> players = in .lines() .skip(1) .map(line -> {
String[] x = pattern.split(line);
return new Player(Integer.parseInt(x[0]), x[1], x[2], x[3], Integer.parseInt(x[4])); }) .collect(Collectors.toList());
Serialize to JSON
Now, completed the list uses Jackson’s ObjectMapper to write the JSON. Check for full details on JSON serialization and deserialization.
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(System.out, players);
Now the whole program’s segment is :
Pattern pattern = Pattern.compile(",");
try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) {
List < Player > players = in .lines().skip(1).map(line - > {
String[] x = pattern.split(line);
return new Player(Integer.parseInt(x[0]), x[1], x[2], x[3], Integer.parseInt(x[4]));
}).collect(Collectors.toList());
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(System.out, players);
}
Convert using CSV Parser
In this method, We use a more complete CSV parser with support for quoted fields and commas embedded within fields and we use the Javascript Collection classes to store the parsed data and convert those to JSON. Here is the complete segment :
try (InputStream in = new FileInputStream(csvFile);) {
CSV csv = new CSV(true, ',', in );
List < String > fieldNames = null;
if (csv.hasNext()) fieldNames = new ArrayList < > (csv.next());
List < Map < String, String >> list = new ArrayList < > ();
while (csv.hasNext()) {
List < String > x = csv.next();
Map < String, String > obj = new LinkedHashMap < > ();
for (int i = 0; i < fieldNames.size(); i++) {
obj.put(fieldNames.get(i), x.get(i));
}
list.add(obj);
}
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(System.out, list);
}
Here is a part of the CSV data that was converted :
rep_file_num,CIK,entity_name,street1,street2,city,state_code,zip,filing_date,doc_type_code
814-00034,0000731812,SIERRA RESOURCES CORP,629 J STREET,SUITE 202,SACRAMENTO,CA,95814,12/30/96,15
814-00053,0000821472,WESTFORD TECHNOLOGY VENTURES LP,17 ACADEMY ST 5TH FLOOR,[NULL],NEWARK,NJ,07102-2905,01/28/04,NO ACT ...
814-00098,0000878932,"EQUUS TOTAL RETURN, INC.",EIGHT GREENWAY PLAZA,SUITE 930,HOUSTON,TX,77046,08/25/16,40-APP/A
Notice that one of the fields in the data is quote because of embedded commas. Here is the converted JSON for that record, which shows that the record has been parsed and converted correctly.
{
"rep_file_num" : "814-00098",
"CIK" : "0000878932",
"entity_name" : "EQUUS TOTAL RETURN, INC.",
"street1" : "EIGHT GREENWAY PLAZA",
"street2" : "SUITE 930",
"city" : "HOUSTON",
"state_code" : "TX",
"zip" : "77046",
"filing_date" : "08/25/16",
"doc_type_code" : "40-APP/A"
}