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

问题描述 投票:0回答:3

我正在使用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()
} 
java csv mapping pojo
3个回答
5
投票

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


0
投票

解析 csv 文件并将其映射到 Java 类有时是一项非常繁忙的工作。有许多可用的 csv 解析器库使我们的生活变得轻松,但它们仍然会在我们现有的代码库中实现它们时造成复杂性。为了解决所有这些问题并使解析过程更加简单,我们可以使用一个名为 csv4pojo 的新 csv 解析库。 csv4pojo 使其在我们现有代码中的实现更加简单,并且它是一个非常轻量级的 Java 库,并且解析速度非常快。它能够解析数百万行数据,并可以在 csv 文件中写入相同数量的数据。它支持 15 种不同的数据类型。

Integer,String,Float,Double,Boolean,Long,Character,Class,Integer[],String[],Float[],Double[],Boolean[],Character[]Long[].

<dependencies>
    <dependency>
        <groupId>org.csv4pojoparser</groupId>
        <artifactId>csv4pojo</artifactId>
        <version>2.0.0</version>
    </dependency>
</dependencies>

在 pom.xml 中添加此 Maven 依赖项并阅读文档这里


-2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.