OpenCSV:将嵌套的Bean映射到CSV文件 [英] OpenCSV: Mapping a Nested Bean to a CSV file
问题描述
我正在尝试将一个bean映射到CSV文件,但是我的bean具有其他嵌套bean作为属性的问题.发生的事情是OpenCSV遍历属性找到一个bean,然后将其放入并映射该bean内部的所有数据,如果找到另一个bean,它将继续运行.如何使用OpenCSV处理嵌套的bean?如何确保它能从嵌套bean映射正确的属性?
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?
推荐答案
在OpenCSV 5.0中,我们可以通过@CsvRecurse
注释映射嵌套的bean,而无需使用MappingStrategy.
In OpenCSV 5.0, we can map nested bean by @CsvRecurse
annotation without using MappingStrategy.
将映射从输入/输出列拆分到成员的能力 多个嵌入式Bean的变量已通过 注释@CsvRecurse.仍然需要一个root bean.
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文件
id,cardNumber,holder
1,1234567 890,abc
根豆
public class DataSet {
@CsvBindByName
private String id;
@CsvRecurse
private MyNumber myNumber;
//getter and setter
}
巢豆
public class MyNumber {
@CsvBindByName
private String cardNumber;
@CsvBindByName
private String holder;
// getter and setter
}
读豆子
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();
}
引用: http://opencsv.sourceforge.net/#multivaluedmap_based_bean_fields_many_to_one_mappings
这篇关于OpenCSV:将嵌套的Bean映射到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!