OpenCSV - 如何将选定的列映射到Java Bean,无论顺序如何? [英] OpenCSV - How to map selected columns to Java Bean regardless of order?
问题描述
我有一个CSV文件,其中包含以下列: id
, fname
,
, lname
,地址
。
I have a CSV file with the following columns: id
, fname
, telephone
, lname
, address
.
我有一个 Person
class with id
, fname
和 lname
数据成员。我只想将这些列映射到CSV文件中的 Person
对象,并丢弃电话
和地址
列。我如何做到这一点?解决方案必须扩展,因为将来会添加更多的列。应该工作,不管列位置。
I have a Person
class with id
, fname
and lname
data members. I want to map only these columns to Person
object from a CSV file and discard telephone
and address
columns. How can I do this? The solution must scale as more columns are added in future. And should work regardless of column position.
在理想的解决方案中,用户只能指定要读取的列,而只能工作。
In an ideal solution user will only specify columns to read and it should just work.
推荐答案
您可以使用 HeaderColumnNameTranslateMappingStrategy 。假设您的CSV包含以下列: Id
, Fname
,电话
, Lname
,地址
。
You can use HeaderColumnNameTranslateMappingStrategy. Lets assume your CSV has the following columns: Id
, Fname
, Telephone
, Lname
, Address
for the sake of simplicity.
CsvToBean<Person> csvToBean = new CsvToBean<Person>();
Map<String, String> columnMapping = new HashMap<String, String>();
columnMapping.put("Id", "id");
columnMapping.put("Fname", "fname");
columnMapping.put("Lname", "lname");
HeaderColumnNameTranslateMappingStrategy<Person> strategy = new HeaderColumnNameTranslateMappingStrategy<Person>();
strategy.setType(Person.class);
strategy.setColumnMapping(columnMapping);
List<Person> list = null;
CSVReader reader = new CSVReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("test.csv")));
list = csvToBean.parse(strategy, reader);
columnMapping将使用 Person
对象。
The columnMapping will map the columns with your Person
object.
这篇关于OpenCSV - 如何将选定的列映射到Java Bean,无论顺序如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!