【问题标题】:How to map csv file to pojo class in java如何将csv文件映射到java中的pojo类
【发布时间】:2015-11-24 05:32:13
【问题描述】:

我正在使用 java maven 插件。我想在 pojo 类中获取employee.csv 文件记录。 我从employee.csv 标题生成的这个pojo 类,pojo 类的所有字段都是字符串类型。现在我想将employee.csv 映射到生成的pojo 类。我的要求是我不想手动指定列名。因为如果我改变csv 文件,然后我必须更改我的代码,以便它应该与任何文件动态映射。比如

firstName,lastName,title,salary 
john,karter,manager,54372

我想把它映射到我已经拥有的 pojo 上

public class Employee
{
  private String firstName;
  private String lastName;
  .
  .
  //getters and setters 
  //toString()
} 

【问题讨论】:

  • 请在发布问题前通过互联网/stackoverflow 搜索
  • 实际上我经历了这个,我也用谷歌搜索了它,但没有根据我的要求得到正确的想法。我的问题有点不同,我会详细说明。请让我编辑我的问题

标签: java csv mapping pojo


【解决方案1】:

uniVocity-parsers 让您轻松映射您的 pojo。

class Employee {

    @Trim
    @LowerCase
    @Parsed
    private String firstName;

    @Parsed
    private String lastName;

    @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 salary; // The attribute name will be matched against the column header in the file automatically.
    ...

}

解析:

BeanListProcessor<Employee> rowProcessor = new BeanListProcessor<Employee>(Employee.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("/path/to/your.csv"))); 

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

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

【讨论】:

    【解决方案2】:

    您可以使用 openCSV jar 来读取数据,然后您可以将每个列的值映射到类属性。 由于安全原因,我无法与您分享我的代码。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多