给出以下示例csv data
name,address,sibling,sibling,sibling
John,MainSt,Sarah,Mike,Greg
以及我要将数据解析为
的示例POJOpublic class Employee {
private String name;
private String address;
private List<String> siblings;
public Employee() { }
public void setName(String name) { ... }
public void setAddress(String address { ... }
public void setSiblings(List<String> siblings) { ... }
}
和以下字段映射
String[] fieldMapping = new String[]{
"name",
"address",
"siblings[0]",
"siblings[1]",
"siblings[2]"
}
以及以下单元处理器
CellProcessors[] processors = new CellProcessors[]{
new NotNull(), // name
new NotNull(), // address
new NotNull(), // siblings[0]
new NotNull(), // siblings[1]
new NotNull() // siblings[2]
}
我希望能够毫无问题地将csv数据解析为Employee
,但是我收到以下异常
org.supercsv.exception.SuperCsvReflectionException: unable to find method setSiblings[0](java.lang.String) in class com.Employee - check that the corresponding nameMapping element matches the field name in the bean, and the cell processor returns a type compatible with the field
这就是我实际解析的方法
List<Employee> deserializedRecords = new ArrayList<>();
try (ICsvBeanReader beanReader = new CsvBeanReader(new FileReader(file), CsvPreferences.STANDARD_PREFERENCE)) {
beanReader.getHeader(true);
Employee model;
while ((model = (Employee) beanReader.read(Employee.class, fieldMapping, processors)) != null) {
deserializedRecords.add(model);
}
}
这几乎遵循here给出的答案,在阅读了SuperCSV文档之后,我并不完全确定为什么会抛出异常。