【问题标题】:SuperCSV - Parsing multiple columns to a ListSuperCSV - 将多列解析为列表
【发布时间】:2014-09-12 13:42:13
【问题描述】:

给定以下示例 csv 数据

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

【问题讨论】:

    标签: java csv supercsv


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 2014-12-25
      • 2017-05-06
      • 2017-01-29
      • 2011-09-13
      • 2016-09-03
      相关资源
      最近更新 更多