Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCSV - register custom converter

So I'm using opencsv to convert a csv to beans. This all works fine with primitive values, but I want to use enums and this is giving some issues.

I'm going through the code, and it seems I need to completely implement a new mappingstrategy to do this just to set a custom convertor. Is there a better way for this?

Current code for the conversion:

CsvToBean<MyType> csvBean = new CsvToBeanBuilder<MyType>(new FileReader(csvFile))
                 .withType(MyType.class)
                 .withIgnoreLeadingWhiteSpace(true)
                 .withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_QUOTES)
                 .build();

I found some questions from 2012 in regards to this, but the answers are no longer applicable for the current opencsv version (4.2).

like image 412
Kristof Plennings Avatar asked Jun 26 '18 06:06

Kristof Plennings


2 Answers

Ok it turns out there's a @CsvCustomBindByName(column = 'foo', converter = Bar.class)

Annotation that does exactly what I want. This class just needs to be of type <T> extends AbstractBeanField<T>

like image 199
Kristof Plennings Avatar answered Sep 17 '22 15:09

Kristof Plennings


So what I have done in similar situations where I have a bunch of primitives but I want a complex object (an object with imbedded objects) is to have an intermediate object. I call them DTO (Data Transfer Objects), though I am sure there is a more appropriate name for it, that openCSV will populate and then the DTO can build the complex object I want from the primitives it contains.

like image 22
Scott Conway Avatar answered Sep 18 '22 15:09

Scott Conway