OpenCSV convert Object with Nested bean to csv

人盡茶涼 提交于 2020-05-15 07:37:57

问题


I am trying to map a bean to a CSV file with selected columns (not all columns) but the problem that my bean has other nested beans as attributes.

Class Student {

@CsvBindByName
private String s_id;

@CsvBindByName
private String name;

@CsvRecurse
private List<Book> books;
}

Class Book {

@CsvBindByName
private String bookName;
private String bookAuthor;
}

I want to map this object to csv file with below format

s_id;name;bookName

I have tried with below code but not getting bookName in csv

ColumnPositionMappingStrategy<Student> mapStrategy
                    = new ColumnPositionMappingStrategy<>();

            mapStrategy.setType(Student.class);

            String[] columns = new String[]{"s_id", "name", "bookName"};
            mapStrategy.setColumnMapping(columns);

            StatefulBeanToCsv<Student> btcsv = new StatefulBeanToCsvBuilder<Student>(writer)
                    .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                    .withMappingStrategy(mapStrategy)
                    .withSeparator(';')
                    .build();

            btcsv.write(students);

Could anyone please help me.

来源:https://stackoverflow.com/questions/60933155/opencsv-convert-object-with-nested-bean-to-csv

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