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);
}
If you look at the Javadoc for CsvMapper.readerWithSchemaFor, it states:
no CSV types can be mapped to arrays or Collections
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With