Search code examples
javaspringjavabeansopencsv

OpenCSV: Mapping a Nested Bean to a CSV file


I am trying to map a bean to a CSV file but the problem that my bean has other nested beans as attributes. What happens is that OpenCSV goes through the attributes finds a bean then goes into it and maps all the data inside of that bean and if it finds another bean it goes on and on. How can I deal withe nested beans using OpenCSV? How can I ensure that it maps the correct attributes from the nested beans?


Solution

  • In OpenCSV 5.0, we can map nested bean by @CsvRecurse annotation without using MappingStrategy.

    The ability to split mappings from input/output columns to member variables of multiple embedded beans has been added through the annotation @CsvRecurse. One root bean is still necessary.

    Csv file

    id,cardNumber,holder
    1,1234567 890,abc
    

    Root bean

    public class DataSet {
    
        @CsvBindByName
        private String id;
    
        @CsvRecurse
        private MyNumber myNumber;
    
        //getter and setter
    }
    

    Nested bean

    public class MyNumber {
    
        @CsvBindByName
        private String cardNumber;
    
        @CsvBindByName
        private String holder;
    
        // getter and setter
    }
    

    Reading beans

      public static void main(String[] args) throws IOException {
            BufferedReader reader = Files.newBufferedReader(Paths.get("path-to-csv-file.csv"));
            List<DataSet> beans = new CsvToBeanBuilder<DataSet>(reader).withType(DataSet.class).build().parse();
        }
    

    Ref: http://opencsv.sourceforge.net/#multivaluedmap_based_bean_fields_many_to_one_mappings