I am using the following code to read the CSV file and parse its data to JSON.
File inputFile = new File("in.csv");
File outputFile = new File("out.json");
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writerWithDefaultPrettyPrinter().writeValue(outputFile,
csvMapper.readerFor(Map.class).with(csvSchema).readValues(inputFile).readAll());
This is working fine and giving me output as follow,
[
{
"Nutrient" : "Calories",
"Amount" : " 289.00",
"Unit" : " kcal"
}, {
"Nutrient" : "Fat",
"Amount" : " 17.35",
"Unit" : " g"
}
]
But the required output is
{
{
"Nutrient" : "Calories",
"Amount" : " 289.00",
"Unit" : " kcal"
}, {
"Nutrient" : "Fat",
"Amount" : " 17.35",
"Unit" : " g"
}
}
Actually I need to read the JSONs files that I have converted from CSVs. Using the following code
String content = Files.readString(filePath);
JSONObject jsonObject1 = new JSONObject(content);
HashMap yourHashMap1 = new Gson().fromJson(jsonObject1.toString(), HashMap.class);
But while I am trying to do it gives me this error.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
Meanwhile json file should start with {
instead of [
and similarly it should end on }
instead ]
.
My goal is to remove this error.