Java POJO到/从CSV,使用字段名称作为列标题

时间:2015-08-28 02:36:17

标签: java csv javabeans pojo code-duplication

我正在寻找一个可以从/向CSV文件读取/写入“简单对象”列表的Java库。

让我们将“简单对象”定义为POJO,其所有字段都是原始类型/字符串。

对象字段和CSV列之间的匹配必须根据字段的名称和列的标题(第一行)进行定义 - 两者必须相同。库不需要额外的匹配信息!如果您只是希望CSV标题与字段名称匹配,那么这些额外的匹配信息是一个可怕的代码重复(关于POJO类的定义)。

最后一个功能是我在我看过的所有库中找不到的东西:OpenCSV,Super CSV和BeanIO。

谢谢!

奥弗

1 个答案:

答案 0 :(得分:1)

uniVocity-parsers不要求您在类中提供字段名称,但如果您需要确定不同的名称,甚至是要执行的数据操作,它会使用注释。它也比你尝试的其他库快得多:

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

}

解析:

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();

披露:我是这个图书馆的作者。它是开源和免费的(Apache V2.0许可证)。