Hi Experts
I have a requirement to convert CSV to JSON. Assume if CSV files have got 2 rows. I need to create a JSON file for each row. This means output will be 2 json files.
Sample Test data: Test.csv
ID,fileName,Type,Direction,Date
1001,File1,PDF,Out,20180518
1002,File2,DOC,Out,20180502
I have written below code for achieving this. The code is working fine and creating individual JSON files for each row as:
File1.txt
{
"ID" : "1001",
"fileName" : "File1",
"Type" : "PDF",
"Direction" : "Out",
"Date" : "20180518"
}
File2.txt
{
"ID" : "1002",
"fileName" : "File2",
"Type" : "DOC",
"Direction" : "Out",
"Date" : "20180502"
}
I need to include the JSON payload in square brackets as root. E.g. Output should be as below. How can I achieve this
File1.txt
[
{
"ID" : "1002",
"fileName" : "File2",
"Type" : "DOC",
"Direction" : "Out",
"Date" : "20180502"
}
]
File2.txt
[
{
"ID" : "1002",
"fileName" : "File2",
"Type" : "DOC",
"Direction" : "Out",
"Date" : "20180502"
}
]
Code:
package com.sap.csv2json;
import java.io.File;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
public class ConvertCSVtoJson {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
File input = new File("C:\\Users\\akellap\\RND\\JSON\\Source\\Test.csv");
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
// Read data from CSV file
List<Object> readAll = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// Write JSON formated data to output.json file
for (Object row : readAll) {
Map<String, String> map = (Map<String, String>) row;
String fileName = map.get("fileName");
File output = new File("C:\\Users\\akellap\\RND\\JSON\\Target\\"+fileName+".txt");
mapper.writerWithDefaultPrettyPrinter().writeValue(output, row);
}
}
}