我们正在使用OpenCSV。的CSV是
id,fname,lname,address.line1,address.line2
bean 是
Person{
String id;
String lname;
String fname;
Address address;
}
Address{
String line1;
String line2;
}
是否可以用opencsv填充嵌套的
Address
对象!opencsv.bean
和opencsv.bean.customconverter
有一些类,这些类似乎可以满足我的要求,但找不到任何示例。我看过
Parse CSV to multiple/nested bean types with OpenCSV?,但答案集中在SuperCSV上,这不是我想要的。
最佳答案
一种选择是创建一个自定义的MappingStrategy类并实现populateNewBean(...)方法,从而为您提供随心所欲地填充bean的手段。
请参阅以下示例:
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;
}
}
输出是
1 Doe John 123 Main St Anytown, USA
2 Dean James 111 Some St Othertown, USA
3 Burger Sam 99 Beach Avenue Sometown, USA
关于java - OpenCSV将CSV转换为嵌套Bean,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39433656/