2014-09-12 51 views
1

对于以下示例CSV数据SuperCSV - 解析多列列表

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

和我想的数据解析成

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) { ... } 
} 

及以下字段映射的例子POJO

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文档后,我不完全是为什么异常会被抛出。

回答

2

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