2014-09-12 48 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)。