I have a task to read a CSV file then do some logic and then create a JSON for that.
I am kind of stuck with required logic before creating JSON, I need to set Max PR VALUE against the SK as PR for all the same SK's.
My Requirement:
CSV:
SK,VR,ST,PR
1000,1000-Q1,10,187
1000,1000-Q2,20,925 // MAX PR against SK
1001,1001-Q1,10,112
1001,1001-Q2,30,120 // MAX PR against SK
Note: Max PR against SK will always be in the last row of its SK.
I have to read CSV here and need to write JSON data as below :
[
{
"SK": "1000",
"VR": "1000-Q1",
"ST": "10",
"PR": "925"
},
{
"SK": "1000",
"VR": "1000-Q2",
"ST": "20",
"PR": "925"
},
{
"SK": "1001",
"VR": "1001-Q1",
"ST": "10",
"PR": "120"
},
{
"SK": "1001",
"VR": "1001-Q2",
"ST": "30",
"PR": "120"
}
]
Edit:
Code
File input = new File("input.csv");
File output = new File("output.json");
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();
// Write JSON formated data to output.json file
mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);
// Write JSON formated data to stdout
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(readAll));