0

我正在尝试将一个 Csv 文件映射到一个使用 CsvMapper 的对象的实例列表,这甚至可能吗?

例子:

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();
    }
   }
}

先感谢您。

4

1 回答 1

0

我找到了自己的解决方案:我使用 common-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();
}

于 2021-07-23T13:26:39.077 回答