gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:56:57 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com