java - 如何将csv文件映射到java中的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

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

最佳答案

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 许可)。

关于java - 如何将csv文件映射到java中的pojo类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33886120/

相关文章:

java - 多线程生成多个线程以及如何等待子线程

python - 查找一组索引,将一个 NumPy ndarray 的行映射到另一个

java - AES 算法安全吗?

java - 获取 String.replaceAll() 删除的内容

sql - Azure 从 Azure 文件服务位置将 csv 文件批量导入 Azure SQL Server

regex - 当存在多个字段分隔符时使用 AWK 忽略字段内的逗号

entity-framework - 用于映射字符串列表或 int 列表 (List<string>) 的 Entity Framework 选项

c# - 使用 AutoMapper 自定义映射

java - 如何打印字符串的每三个字符? java

python - 如何在 Python 中查找并替换每行特定字符后面的文本?