OpenCSV: Mapping a Nested Bean to a CSV file

流过昼夜 提交于 2020-01-05 01:41:09

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/59226581/opencsv-mapping-a-nested-bean-to-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!