【问题标题】:Java POJO to/from CSV, using field names as column titlesJava POJO 到/从 CSV,使用字段名称作为列标题
【发布时间】:2015-08-28 02:36:16
【问题描述】:

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

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

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

最后一个功能是我在我查看的所有库中都找不到的:OpenCSV、Super CSV 和 BeanIO。

谢谢!!

报价

【问题讨论】:

    标签: java csv javabeans pojo code-duplication


    【解决方案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 许可)。

    【讨论】:

    • 如何以迭代方式流式传输 bean?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多