OpenCSV将csv转换为嵌套bean

时间:2016-09-11 07:02:17

标签: java csv opencsv

我们正在使用OpenCSV。 csv是

id,fname,lname,address.line1,address.line2

豆子是

Person{
  String id;
  String lname;
  String fname;
  Address address;
}

Address{
  String line1;
  String line2;  
}

是否可以使用opencsv填充嵌套的Address对象! opencsv.beanopencsv.bean.customconverter有一些类似乎可以做我想要的但我找不到任何样本。

我见过 Parse CSV to multiple/nested bean types with OpenCSV?但答案主要集中在SuperCSV,这不是我想要的。

2 个答案:

答案 0 :(得分:1)

一种选择是创建自定义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

答案 1 :(得分:0)

在OpenCSV 5.0中,我们可以通过@CsvRecurse注释映射嵌套的bean。文档如下

  

指示映射策略在成员变量内部查找   进一步的贴图注释。

请检查OpenCSV: Mapping a Nested Bean to a CSV file