Search code examples
javaspringcsvopencsv

Read CSV files with known and unknown columns in java


I'm wondering if there is a way to read csv files with known and unknown columns.

For example, the column in the first csv file is: id, firstname, lastname, city, country the unknown columns are city and country

the second csv file is:

id, firstname, lastname, phone number the unknown column is phone number

The Object that I want to parse into is:

public class Person {

    Long id;
    String firstname;
    String lastname;

    Map<String,String> additionalInfo;

}

The additionalInfo map will contain as keys the 'unknown' columns and the values will be the row value in that column.

Any ideas?

Thanks.


Solution

  • OpenCSV allows you to do something similar to this using @CsvBindAndJoinByName annotation. Taken from the docs:

    public class Demonstration {
    
       @CsvBindByName(column = "index")
       private String index;
    
       @CsvBindAndJoinByName(column = ".*", elementType = String.class)
       private MultiValuedMap<String, String> theRest;
    
       // Getters and setters go here
    }
    

    The same docs mention a caveat: you have to be careful not to have overlapping patterns if you have multiple @CsvBindAndJoinByName, otherwise the result is undefined.