Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Jackson: Parsing a csv file into an object containing a List of objects

Tags:

java

csv

jackson

I am trying to parse a csv file using Jackson CsvParser into an object that also contains a list of another class.

So the first 2 columns contain data that needs to be bound to the parent class and the data afterwards would need to be bound to another class.

public class Person {
    private String name;
    private String age;
    private List<CarDetails> carDetails;

    //Getters+setters
}

public class CarDetails {
    private String carMake;
    private String carRegistration;

    //Getters+setters
}

The log to be parsed would look like:

John Doe, 30, Honda, D32GHF

Or in another log of users all with 2 cars it may look like:

Jane Doe, 29, Mini, F64RTZ, BMW, T56DFG 

To parse the initial 2 items of data to the "Person" class is no problem.

CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.builder()
    .addColumn("name")
    .addColumn("age")

for(numberOfCars=2; numberOfCars!=0 ; numberOfCars--)
    schema = schema.rebuild()
        .addColumn("carMake")
        .addColumn("carRegistration")

MappingIterator<Map.Entry> it = mapper
    .reader(Person.class)
    .with(schema)
    .readValues(personLog);
    List<Person> people = new ArrayList<Person>();
    while (it.hasNextValue()) {
        Person person = (Person) it.nextValue();
        people.add(person);
    }

But I do not know how to parse the CarDetails. It seems like I have to be able to search for the value, create a new CarDetails object and add it to the Person object, but I can't see how to extract that information.


My solution is the following:

List<Person> people = new ArrayList<Person>();

MappingIterator<Map<?,?>> it = mapper.reader(schema).withType(Map.class).readValues(personLog);
while(it.hasNextValue()) {
    Person person = new Person();
    CarDetails = new CarDetails();
    Map<?,?> result = it.nextValue();
    person.setName(result.get("name").toString());
    carDetails.setCarMake(result.get("carMake").toString());
    person.addCarDetails(carDetails);
    people.add(person);
}    
like image 412
DanF7 Avatar asked Sep 26 '12 13:09

DanF7


1 Answers

If you look at the Javadoc for CsvMapper.readerWithSchemaFor, it states:

no CSV types can be mapped to arrays or Collections

like image 72
David Grant Avatar answered Sep 21 '22 15:09

David Grant