Ofer
Ofer

Reputation: 289

Java POJO to/from CSV, using field names as column titles

I’m looking for a Java library that can read/write a list of “simple objects” from/to a CSV file.

Let’s define a “simple object” as a POJO that all its fields are primitive types/strings.

The matching between an object’s field and a CSV column must be defined according to the name of the field and the title (first row) of the column - the two must be identical. No additional matching information should be required by the library! Such additional matching information is a horrible code duplication (with respect to the definition of the POJO class) if you simply want the CSV titles to match the field names.

This last feature is something I’ve failed to find in all the libraries I looked at: OpenCSV, Super CSV and BeanIO.

Thanks!!

Ofer

Upvotes: 1

Views: 1445

Answers (1)

Jeronimo Backes
Jeronimo Backes

Reputation: 6289

uniVocity-parsers does not require you to provide the field names in your class, but it uses annotations if you need to determine a different name, or even data manipulation to be performed. It is also way faster than the other libraries you tried:

class TestBean {

    @NullString(nulls = { "?", "-" }) // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @Parsed(defaultNullRead = "0") // if a value resolves to null, it will be converted to the String "0".
    private Integer quantity; // The attribute name will be matched against the column header in the file automatically.

    @Trim
    @LowerCase
    @Parsed
    private String comments;
    ...

}

To parse:

BeanListProcessor<TestBean> rowProcessor = new BeanListProcessor<TestBean>(TestBean.class);

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(parserSettings);

//And parse!
//this submits all rows parsed from the input to the BeanListProcessor
parser.parse(new FileReader(new File("/examples/bean_test.csv"))); 

List<TestBean> beans = rowProcessor.getBeans();

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

Upvotes: 1

Related Questions