Skip to content
Advertisement

How to map a CSV to Object with List using CsvMapper?

I’m trying to map a Csv file to an Object what instances List of Objects using CsvMapper, is that even possible?

Example:

Content of Csv file (without header):

Field 1: name

Field 2: gender

Field 3: hobby (List comma separated)

Field 4: relation

Bob;male;riding,swimming,dance;single

Example class:

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

Thank you in advance.

Advertisement

Answer

I found myself a solution: I used common-cdv (apache) as a plugin instead of Jackson CsvMapper.

My solution:

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement