我有一个要求,
想知道是否可以使用 OpenCSV 注释进行类似的操作。
输入CSV
User ID, First Name, Last Name, Worked Minutes
1234,Jon,Snow,60
1235,Rob,Stark,30
bean
public class Employee {
@CsvBindByName(column = "Employee ID")
private String userId;
//this should be "First Name, Last Name"
private String employeeName;
//this should be Worked Minutes/60
private String workedHours;
//getters and setters
}
我设法做到这一点的唯一方法是将列映射为单独的属性(
userId
、 firstName
、 lastName
、 workedMinutes
),然后修改 employeeName
和 workedHours
getter 方法,但我觉得应该有更好的方法来做到这一点。
最佳答案
我不知道如何用 OpenCSV 做到这一点,但我写了一个名为 jflat-core 的库。可以处理对象和平面文件之间的这种复杂映射。
CSVReader<Employee> csvReader = CSVReader
.createWithHeaderMapping(Employee.class,
new String[] {"User ID", "First Name", "Last Name", "Worked Minutes"},
new String[] {"userId", "firstName", "lastName", "workedHours" });
//register a special converter for the property workedHours
csvReader.registerConverter("workedHours",
minutes -> String.valueOf(Double.valueOf(minutes)/60.0));
List<Employee> employees = csvReader.readAllWithCallback("employees.csv",
//The callback can be used to help map attributes from the raw record to the target bean
(record, employee) -> {
String name = String.format("%s %s", record.get("First Name"), record.get("Last Name"));
employee.setEmployeeName(name);
});
assertEquals(2, employees.size());
assertEquals("Jon Snow", employees.get(0).getEmployeeName());
assertEquals("0.5", employees.get(1).getWorkedHours());
关于java - OpenCSV - 将多个 CSV 列映射到单个 bean 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769312/