如何在java中将csv文件映射到pojo类

如何在java中将csv文件映射到pojo类,java,csv,mapping,pojo,Java,Csv,Mapping,Pojo,我正在使用java maven插件。我想在pojo类中获取employee.csv文件记录。 我从employee.csv头生成的这个pojo类,pojo类的所有字段都是字符串类型。现在我想将employee.csv映射到生成的pojo类。我的要求是我不想手动指定列名。因为如果我更改csv文件,我必须再次更改代码,以便它可以与任何文件动态映射。比如说 firstName,lastName,title,salary john,karter,manager,54372 我想把这个映射到pojo,

我正在使用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()
} 

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

允许您轻松映射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();
BeanListProcessor rowProcessor=新的BeanListProcessor(Employee.class);
CsvParserSettings parserSettings=新的CsvParserSettings();
setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
CsvParser parser=新的CsvParser(parserSettings);
//和解析!
//这会将从输入解析的所有行提交给BeanListProcessor
parser.parse(新文件阅读器(新文件(“/path/to/your.csv”));
List bean=rowProcessor.getBeans();

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

在发布问题之前,请通过internet搜索/stackoverflow的可能副本实际上我已经看过了,我也在谷歌上搜索了它,但没有根据我的要求得到正确的想法。我的问题有点不同,我会详细说明。请允许我编辑我的问题。请您详细说明。当您阅读csv时,根据我的理解,它将以“”分隔,因此您可以使用它的类[单击我](,char))将其打断