Cha*_*are 3 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
Run Code Online (Sandbox Code Playgroud)
我想将其映射到我已经有的 pojo
public class Employee
{
private String firstName;
private String lastName;
.
.
//getters and setters
//toString()
}
Run Code Online (Sandbox Code Playgroud)
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.
...
}
Run Code Online (Sandbox Code Playgroud)
解析:
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();
Run Code Online (Sandbox Code Playgroud)
披露:我是这个库的作者。它是开源且免费的(Apache V2.0 许可证)。
| 归档时间: |
|
| 查看次数: |
13463 次 |
| 最近记录: |