I have a code which converts CSV File to JSON String
public static Optional<String> csvToJSON(String filePath) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),
StandardCharsets.UTF_8))) {
String inputString;
StringBuilder csvStringBuilder = new StringBuilder();
while (!Objects.isNull(inputString = br.readLine())) {
csvStringBuilder.append(inputString).append(NEW_LINE);
}
if (Objects.isNull(CDL.toJSONArray(csvStringBuilder.toString()))) {
return Optional.empty();
}
String csvToJsonString = CDL.toJSONArray(csvStringBuilder.toString()).toString()
.replaceAll(NON_ASCII_CHARACTERS, BLANK);
return Optional.of(csvToJsonString);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
For a CSV File like this
ID,Colour
"1","Black,White"
"2","Black,White,Blue"
"3","Black"
"4","Black,White"
The file is currently returning a JSON String which looks like this:
[
{
"ID":"1"
"Colour":"Black,White"
},
{
"ID":"2"
"Colour":"Black,White,Blue"
},
{
"ID":"3"
"Colour":"Black"
},
{
"ID":"4"
"Colour":"Black,White"
}
]
However, I want that while reading and converting the CSV File, if the header is "Colour", in the JSON String the colours should be printed as an array of strings
[
{
"ID":"1"
"Colour":["Black","White"]
},
{
"ID":"2"
"Colour":["Black","White","Blue"]
},
{
"ID":"3"
"Colour":["Black"]
},
{
"ID":"4"
"Colour":["Black","White"]
}
]
Where can I apply the splitting of strings logic in the code pasted above?