Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 981
yasseen Avatar asked Dec 07 '19 13:12

yasseen


1 Answers

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

like image 61
Byaku Avatar answered Oct 03 '22 14:10

Byaku