Java Jackson: parsing a csv file into an object containing a list of objects

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 should be bound to the parent class, and subsequent data should 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 analyzed log will look like this:

John Doe, 30, Honda, D32GHF

Or in another log of users who have 2 machines, it might look like this:

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

There is no problem for the Person class to parse the original 2 data elements.

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 CarDetails. It seems like I need to find the value, create a new CarDetails object and add it to the Person object, but I don’t see how to extract this information.


My solution is as follows:

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);
}    
+5
source share
1
+4

All Articles