如何使用CsvMapper将CSV映射到具有列表的对象



我正在尝试使用CsvMapper将Csv文件映射到Object what instances List of Objects,这可能吗?

示例:

Csv文件的内容(无标题(:

字段1:名称

领域2:性别

字段3:爱好(列表逗号分隔(

字段4:关系

Bob;male;riding,swimming,dance;single

示例类:

@AllArgsConstructor(access = AccessLevel.PRIVATE)
Class User {
String name;
String gender;
List<Hobby> hobbys;
String relation;
Boolean check;
int index;
public static User from(String name,
String gender,
List<Hobby> hobbys,
String relation) {
------ SOME LOGIC -----
return new User(name,
gender,
hobbys,
relation,
index)
}
}
Class UserCreator{
public List<User> create(File csvFile){
//Now my Problem how can I map the csvFile to User Object???
//my attempts
CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = CsvSchema
.emptySchema()
.withoutHeader()
.withColumnSeparator(',')
.withLineSeparator(";");
try {
//here its crashes, my problem ist how can I map it to the User object?
MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class)
.with(csvSchema)
.readValues(file);
System.out.println("test");
} catch (IOException e) {
e.printStackTrace();
}
}
}

提前谢谢。

我找到了一个解决方案:我使用公共cdv(apache(作为插件,而不是Jackson CsvMapper。

我的解决方案:


public List<User> create(File csvFile){
Reader reader = new FileReader(file);
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withDelimiter(';').withIgnoreEmptyLines());
csvParser.forEach(csvRecord -> {
String name = csvRecord.get(0);
String gender = csvRecord.get(1);
List<Hobby> hobbys = List.of(csvRecord.get(2).split(','));
String relation = csvRecord.get(3);
.......
});
csvParser.close();
}

相关内容

  • 没有找到相关文章

最新更新