2015-08-28 67 views
1

我正在尋找一個Java庫,它可以從/向CSV文件讀取/寫入「簡單對象」列表。使用字段名稱作爲列標題的Java POJO到CSV,使用字段名稱

讓我們定義一個「簡單對象」作爲POJO,它的所有字段都是原始類型/字符串。

對象的字段和CSV柱之間的匹配,必須根據該字段的列的名稱和標題(第一行)被定義 - 兩個必須是相同的。圖書館不需要額外的匹配信息!如果您只是希望CSV標題與字段名稱匹配,則此類附加匹配信息是一個可怕的代碼重複(相對於POJO類的定義)。

最後一個功能是我在所有我看過的庫中都找不到的:OpenCSV,Super CSV和BeanIO。

謝謝!

奧弗

回答

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許可證)。

相關問題