In the tutorial, Grokonez shows how to convert CSV File to JSON String or JSON File and vice versa with Java language by examples.
I. Dependencies
org.apache.commons commons-csv 1.5 com.fasterxml.jackson.core jackson-databind 2.8.5
II. CSV to JSON
CSV File to JSON String
We do 2 steps:
– Step 1: Read CSV File into Java List Objects
– Step 2: Convert Java List Objects to JSON String
-> CSV File:
Customer.java
:
package com.ozenero.convertcsv2json; public class Customer { private String id; private String name; private String address; private int age; public Customer() { } public Customer(String id, String name, String address, int age) { this.id = id; this.name = name; this.address = address; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", age=" + age + "]"; } }
-> Converting Implementation:
package com.ozenero.convertcsv2json; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class ConvertCsv2Json { public static void main(String[] args) { Listcustomers = readCsvFile("customers.csv"); String jsonString = convertJavaObject2JsonString(customers); System.out.println(jsonString); } /** * * Read CSV File into Memory * @param filePath * @return */ private static List readCsvFile(String filePath) { BufferedReader fileReader = null; CSVParser csvParser = null; List customers = new ArrayList (); try { fileReader = new BufferedReader(new FileReader(filePath)); csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim()); Iterable csvRecords = csvParser.getRecords(); for (CSVRecord csvRecord : csvRecords) { Customer customer = new Customer( csvRecord.get("id"), csvRecord.get("name"), csvRecord.get("address"), Integer.parseInt(csvRecord.get("age")) ); customers.add(customer); } } catch (Exception e) { System.out.println("Reading CSV Error!"); e.printStackTrace(); } finally { try { fileReader.close(); csvParser.close(); } catch (IOException e) { System.out.println("Closing fileReader/csvParser Error!"); e.printStackTrace(); } } return customers; } /** * * Convert Java Object to JSON String * * @param customers * @return */ private static String convertJavaObject2JsonString(List customers) { ObjectMapper mapper = new ObjectMapper(); String jsonString = ""; try { jsonString = mapper.writeValueAsString(customers); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonString; } }
-> Output:
[{"id":"1","name":"Jack Smith","address":"Massachusetts","age":23},{"id":"2","name":"Adam Johnson","address":"New York","age":27},{"id":"3","name":"Katherin Carter","address":"Washington DC","age":26},{"id":"4","name":"Jack London","address":"Nevada","age":33},{"id":"5","name":"Jason Bourne","address":"California","age":36}]
-> Pretty Format:
[ { "id":"1", "name":"Jack Smith", "address":"Massachusetts", "age":23 }, { "id":"2", "name":"Adam Johnson", "address":"New York", "age":27 }, { "id":"3", "name":"Katherin Carter", "address":"Washington DC", "age":26 }, { "id":"4", "name":"Jack London", "address":"Nevada", "age":33 }, { "id":"5", "name":"Jason Bourne", "address":"California", "age":36 } ]
CSV File to JSON File
We do 2 steps:
– Step 1: Read CSV File into Java List Objects
– Step 2: Convert Java List Objects to JSON File
-> Implementation:
package com.ozenero.convertcsv2json; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import com.fasterxml.jackson.databind.ObjectMapper; public class ConvertCsv2Json { public static void main(String[] args) { // Step 1: Read CSV File into Java List Objects Listcustomers = readCsvFile("customers.csv"); // Step 2: Convert Java List Objects to JSON File convertJavaObject2JsonFile(customers, "customers.json"); } /** * * Read CSV File into Memory * @param filePath * @return */ private static List readCsvFile(String filePath) { BufferedReader fileReader = null; CSVParser csvParser = null; List customers = new ArrayList (); try { fileReader = new BufferedReader(new FileReader(filePath)); csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim()); Iterable csvRecords = csvParser.getRecords(); for (CSVRecord csvRecord : csvRecords) { Customer customer = new Customer( csvRecord.get("id"), csvRecord.get("name"), csvRecord.get("address"), Integer.parseInt(csvRecord.get("age")) ); customers.add(customer); } } catch (Exception e) { System.out.println("Reading CSV Error!"); e.printStackTrace(); } finally { try { fileReader.close(); csvParser.close(); } catch (IOException e) { System.out.println("Closing fileReader/csvParser Error!"); e.printStackTrace(); } } return customers; } /** * Convert Java Object to JSON File * @param customers * @param pathFile */ private static void convertJavaObject2JsonFile(List customers, String pathFile) { ObjectMapper mapper = new ObjectMapper(); File file = new File(pathFile); try { // Serialize Java object info JSON file. mapper.writeValue(file, customers); } catch (IOException e) { e.printStackTrace(); } } }
III. JSON to CSV
JSON String to CSV File
We do 2 steps:
– Convert JSON String to Java List Objects
– Write Java List Objects to CSV File
-> Implementation:
package com.ozenero.convertcsv2json; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class ConvertJson2Csv { public static void main(String[] args) { // Step 1: Read JSON File to List Objects String jsonStr = "[{\"id\":\"1\",\"name\":\"Jack Smith\",\"address\":\"Massachusetts\",\"age\":23},{\"id\":\"2\",\"name\":\"Adam Johnson\",\"address\":\"New York\",\"age\":27},{\"id\":\"3\",\"name\":\"Katherin Carter\",\"address\":\"Washington DC\",\"age\":26},{\"id\":\"4\",\"name\":\"Jack London\",\"address\":\"Nevada\",\"age\":33},{\"id\":\"5\",\"name\":\"Jason Bourne\",\"address\":\"California\",\"age\":36}]"; Listcustomers = convertJsonString2Objects(jsonStr); // Step 2: Write List Objects to CSV File writeListObjects2CsvFile(customers, "customers.csv"); } /** * * Convert JSON String to List Java Objects * * @param pathFile * @return */ private static List convertJsonString2Objects(String jsonString){ List customers = null; try { customers = new ObjectMapper().readValue(jsonString, new TypeReference >(){}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return customers; } /** * Write List Objects to CSV File * * @param customers */ private static void writeListObjects2CsvFile(List
customers, String pathFile) { final String[] CSV_HEADER = { "id", "name", "address", "age" }; FileWriter fileWriter = null; CSVPrinter csvPrinter = null; try { fileWriter = new FileWriter(pathFile); csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader(CSV_HEADER)); for (Customer customer : customers) { List data = Arrays.asList( customer.getId(), customer.getName(), customer.getAddress(), String.valueOf(customer.getAge())); csvPrinter.printRecord(data); } } catch (Exception e) { System.out.println("Writing CSV error!"); e.printStackTrace(); } finally { try { fileWriter.flush(); fileWriter.close(); csvPrinter.close(); } catch (IOException e) { System.out.println("Flushing/closing error!"); e.printStackTrace(); } } } }
JSON File to CSV File
We do 2 steps:
– Read JSON File to Java List Objects
– Write Java List Objects to CSV File
-> Implementation:
package com.ozenero.convertcsv2json; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class ConvertJson2Csv { public static void main(String[] args) { // Step 1: Read JSON File to List Objects Listcustomers = readJSONFile2ListObjects("customers.json"); // Step 2: Write List Objects to CSV File writeListObjects2CsvFile(customers, "customers.csv"); } /** * * Read JSON File to List Java Objects * * @param pathFile * @return */ private static List readJSONFile2ListObjects(String pathFile) { InputStream inJson = Customer.class.getResourceAsStream(pathFile); List customers = null; try { customers = new ObjectMapper().readValue(inJson, new TypeReference >(){}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return customers; } /** * Write List Objects to CSV File * * @param customers */ private static void writeListObjects2CsvFile(List
customers, String pathFile) { final String[] CSV_HEADER = { "id", "name", "address", "age" }; FileWriter fileWriter = null; CSVPrinter csvPrinter = null; try { fileWriter = new FileWriter(pathFile); csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader(CSV_HEADER)); for (Customer customer : customers) { List data = Arrays.asList( customer.getId(), customer.getName(), customer.getAddress(), String.valueOf(customer.getAge())); csvPrinter.printRecord(data); } } catch (Exception e) { System.out.println("Writing CSV error!"); e.printStackTrace(); } finally { try { fileWriter.flush(); fileWriter.close(); csvPrinter.close(); } catch (IOException e) { System.out.println("Flushing/closing error!"); e.printStackTrace(); } } } }