问题
We are using OpenCSV. The csv is as
id,fname,lname,address.line1,address.line2
The beans are
Person{
String id;
String lname;
String fname;
Address address;
}
Address{
String line1;
String line2;
}
Is it possible to fill the nested Address
object with opencsv !
The opencsv.bean
and opencsv.bean.customconverter
have some classes which seems can do what I want but I could not find any samples.
I have seen the Parse CSV to multiple/nested bean types with OpenCSV? but the answer focus on SuperCSV, which is not what I am looking for.
回答1:
One option is to create a custom MappingStrategy class and implement the method populateNewBean(...) providing you means to populate beans as you like.
See this example:
public void example() {
Reader in = new StringReader(
"1,Doe,John,123 Main St,\"Anytown, USA\"\n" +
"2,Dean,James,111 Some St,\"Othertown, USA\"\n" +
"3,Burger,Sam,99 Beach Avenue,\"Sometown, USA\"\n");
CsvToBeanBuilder<Person> builder = new CsvToBeanBuilder<Person>(in)
.withMappingStrategy(new PersonMappingStrategy());
CsvToBean<Person> ctb = builder.build();
for (Person person : ctb.parse()) {
System.out.println(
person.id
+ "\t" + person.lname
+ "\t" + person.fname
+ "\t" + person.address.line1
+ "\t" + person.address.line2);
}
}
class Person {
String id;
String lname;
String fname;
Address address;
}
class Address {
String line1;
String line2;
}
class PersonMappingStrategy extends ColumnPositionMappingStrategy {
public PersonMappingStrategy() {
this.setType(Person.class);
}
@Override
public Object populateNewBean(String[] line) throws CsvBeanIntrospectionException, CsvRequiredFieldEmptyException,
CsvDataTypeMismatchException, CsvConstraintViolationException, CsvValidationException {
Person person = new Person();
person.id = line[0];
person.lname = line[1];
person.fname = line[2];
person.address = new Address();
person.address.line1 = line[3];
person.address.line2 = line[4];
return person;
}
}
The output is
1 Doe John 123 Main St Anytown, USA
2 Dean James 111 Some St Othertown, USA
3 Burger Sam 99 Beach Avenue Sometown, USA
回答2:
In OpenCSV 5.0, we can map nested bean by @CsvRecurse
annotation. Documentation as follow
Instructs a mapping strategy to look inside a member variable for further mapping annotations.
please check OpenCSV: Mapping a Nested Bean to a CSV file
来源:https://stackoverflow.com/questions/39433656/opencsv-convert-csv-to-nested-bean