Reputation: 2519
I have a CSV file delimited by a single space character, like so-
<HEADING ROW>
a b c,d,e,f
m n o,p,q
Here, the last element is a list of strings concatenated with the comma separator. I'm currently using the OpenCsv
library to parse this CSV file into a list of POJOs.
Here is my POJO definition:
import com.opencsv.bean.CsvBindByName;
import java.util.List;
public class Foo {
@CsvBindByName(column = "heading1", required = true)
private Long first;
@CsvBindByName(column = "heading2", required = true)
private String third;
@CsvBindByName(column = "heading3", required = true)
private List<String> fourth;
}
So all the fields in this object are of different types, especially the last one, which is of a list type, and can be of any non-zero length. Here's my code to map the CSV file to a list of these objects:
public List<Foo> readCsvFromPath(final String filePath) throws IOException {
try (Reader reader = Files.newBufferedReader(Paths.get(filePath));) {
CsvToBean<Foo> csvToBean = new CsvToBeanBuilder<Foo>(reader)
.withSeparator(' ')
.withType(Foo.class)
.build();
return csvToBean.parse();
}
}
What I'm not sure about here is how can the last element of the CSV file, ie, "c,d,e,f" or "o,p,q" will get respectively mapped to lists like {"c", "d", "e", "f"}
and {"o", "p", "q"}
?
Upvotes: 3
Views: 4881
Reputation: 4088
You can use @CsvBindAndSplitByName
.
Replace this code
@CsvBindByName(column = "heading3", required = true)
private List<String> fourth;
with
@CsvBindAndSplitByName(column = "heading3", required = true, elementType = String.class, splitOn = ",")
private List<String> fourth;
Upvotes: 5