OpenCSV not converting empty string to null POJO field

113 Views Asked by At

Using OpenCSV 5.9

How should I be configuring my CsvToBeanBuilder to convert empty Strings to null on my POJO. For example, the I'd expect the following POJO to have a null value for "lastName" - instead the value is "". I thought setting .withFieldAsNull(CSVReaderNullFieldIndicator.BOTH) would work but I'm still seeing empty Strings as the value for lastName instead of null

CSV example

"FIRST_NAME","LAST_NAME"
"Bob",""

POJO

@Data
@NoArgsConstructor
@EqualsAndHashCode
public class Person {

  @CsvBindByName(column = "FIRST_NAME")
  private String firstName;

  @CsvBindByName(column = "LAST_NAME")
  private String lastName;

}

Parser

@Slf4j
@Component
@Qualifier("CsvParser")
public class CsvParser implements FileParser {

  @Override
  public List<Person> parse(InputStream inputStream) {
    log.debug("Parsing InputStream as CSV");

    return new CsvToBeanBuilder<Person>(new CSVReader(new InputStreamReader(inputStream)))
        .withType(Person.class)
        .withSeparator(',')
        .withIgnoreLeadingWhiteSpace(true)
        .withIgnoreEmptyLine(true)
        .withFieldAsNull(CSVReaderNullFieldIndicator.BOTH)
        .build()
        .parse();
  }
}

Pom dependency

    <dependency>
      <groupId>com.opencsv</groupId>
      <artifactId>opencsv</artifactId>
      <version>5.9</version>
    </dependency>
1

There are 1 best solutions below

0
Larry On

I ended up just writing a custom converter and using the @CsvCustomBindByName.

POJO

@Data
@NoArgsConstructor
@EqualsAndHashCode
public class Person {

  @CsvCustomBindByName(column = "FIRST_NAME", converter = NonEmptyStringConverter.class)
  private String firstName;

  @CsvCustomBindByName(column = "LAST_NAME", converter = NonEmptyStringConverter.class)
  private String lastName;
}

Converter

public class NonEmptyStringConverter extends AbstractBeanField {

  @Override
  protected String convert(String s)
      throws CsvDataTypeMismatchException, CsvConstraintViolationException {
    return StringUtils.isNotEmpty(s) ? s : null;
  }