SuperCSV - 将多个列解析为List

时间:2014-09-12 13:42:14

标签: java csv supercsv

给出以下示例csv data

name,address,sibling,sibling,sibling John,MainSt,Sarah,Mike,Greg

以及我要将数据解析为

的示例POJO
public 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文档之后,我并不完全确定为什么会抛出异常。

1 个答案:

答案 0 :(得分:2)

您正在使用不支持索引(或深度)映射的CsvBeanReader。您正在寻找CsvDozerBeanReader(示例here)。