2

I do know the header, but the header is parsed separately. I am using a pojo with annotations and setting it as type.

My code looks like this:

 CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
                .withSeparator(SEPERATOR)
                .withIgnoreLeadingWhiteSpace(true)
                .withType(MyObject.class)
                .build();

When I iterate, I get MyObject with all null values. MyObject is the pojo with fields annotated with column names.

Is there a way to set headers in opencsv?

J.J
  • 633
  • 1
  • 6
  • 14

2 Answers2

0

There's a MappingStrategy on CsvToBean. ColumnPositionMappingStrategy will allow you to link the columns to the bean properties by name.

For example:

    CsvToBean<MyObject> bb = new CsvToBeanBuilder<MyObject>(reader)
            .withSeparator(SEPERATOR)
            .withIgnoreLeadingWhiteSpace(true)
            .withType(MyObject.class)
            .build();

    ColumnPositionMappingStrategy<MyObject> mappingStrategy = new ColumnPositionMappingStrategy<>();
    mappingStrategy.setType(MyObject.class);
    mappingStrategy.setColumnMapping("property1", "property2");
    bb.setMappingStrategy(mappingStrategy);

    bb.parse();
df778899
  • 10,703
  • 1
  • 24
  • 36
  • Thanks, but that won't work. I can't use column positions because of other requirements. I must use column names. When I use other mapping strategies, header is automatically picked by reading the first line. Because I don't have header on first line, the mapping won't work. It seems like I will have to write a custom mapping strategy by extending existing srategies or implementing the interface. None of the existing strategies would do. – J.J Oct 01 '18 at 21:05
0

As I mentioned in my last comment, I ended up implementing a custom strategy to fix my issue.

public class BlahMappingStrategy extends HeaderColumnNameMappingStrategy {
List<String> headerList;

public BlahMappingStrategy(List<String> headerList) {
    this.headerList = headerList;
}

@Override
public void captureHeader(CSVReader reader) throws IOException, CsvRequiredFieldEmptyException {
    if (this.type == null) {
        throw new IllegalStateException(ResourceBundle.getBundle("opencsv", this.errorLocale).getString("type.unset"));
    } else {
        String [] header = headerList.toArray(new String[headerList.size()]);
        this.headerIndex.initializeHeaderIndex(header);
    }
}

}

That is all that was needed.

J.J
  • 633
  • 1
  • 6
  • 14