gpt4 book ai didi

java - SuperCSV - 将多列解析为列表

转载 作者:行者123 更新时间:2023-11-30 03:45:35 24 4
gpt4 key购买 nike

给出以下 csv 数据示例

姓名、地址、 sibling 、 sibling 、 sibling
约翰、MainSt、莎拉、迈克、格雷格

以及我想要将数据解析成的示例 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:无法在 com.Employee 类中找到方法 setSiblings[0](java.lang.String) - 检查相应的 nameMapping 元素是否与 bean 中的字段名称匹配,并且单元处理器返回与字段兼容的类型

这就是我进行实际解析的方式

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

最佳答案

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

关于java - SuperCSV - 将多列解析为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com