I Have requirement to convert csv to json and generate multiple json files as per records available in csv file.
Please find below code:
import java.io.File;
import java.lang.*;
import java.util.Arrays;
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("D:\\Monika\\Test.csv");
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
// Read data from CSV file
List<Object> readAll = Arrays.asList(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("D:\\Monika\\"+fileName+".txt");
mapper.writerWithDefaultPrettyPrinter().writeValue(output, row);
}
}
}
i am getting error on line" List<Object> readAll = Arrays.asList(csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll());".
Kindly suggest.