OpenCSV - 无论顺序如何,如何将选定的列映射到 Java Bean? [英] OpenCSV - How to map selected columns to Java Bean regardless of order?
问题描述
我有一个包含以下列的 CSV 文件:id
、fname
、telephone
、lname
、<代码>地址代码>.
I have a CSV file with the following columns: id
, fname
, telephone
, lname
, address
.
我有一个带有 id
、fname
和 lname
数据成员的 Person
类.我只想将这些列映射到 CSV 文件中的 Person
对象并丢弃 telephone
和 address
列.我怎样才能做到这一点?该解决方案必须随着未来添加更多列而扩展.并且无论列位置如何都应该工作.
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
、Telephone
、Lname
、Address
为简单起见.
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屋!