0

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

1 Answer 1

0

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;
  }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.