Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCSV convert csv to nested bean

Tags:

java

csv

opencsv

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.

like image 807
Alireza Fattahi Avatar asked Sep 11 '16 07:09

Alireza Fattahi


1 Answers

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
like image 105
haba713 Avatar answered Nov 15 '22 23:11

haba713