vendredi 27 février 2015

Parse CSV file into List of Object arrays in java

I'm trying to parse a csv file into a list of object arrays.


Here is one example of the csv file



Type.Country,Type.Device,Sequence.id
US,PC,1
US,Tablet,2
UK,PC,3


I want to get a List list where each Object[] will contain two objects, Type and Sequence. So I can call the following code to get the output:



print(list.get(1)[1].getId());


output: 2


I created 2 POJO classes: Type and Sequence but the question is how can I parse the header information and get the column ids mapped to the POJO fields. It's easy to hard code the logic. But the csv files changes very often and I want to modify only the POJO classes to accommodate those changes, leaving the mapping logic general and unchanged.


I used OpenCSV to get the lines from csv but ran into trouble parsing the headers. Reflection can help but the code will be very messy. Is there any other open source tool that can help?






Aucun commentaire:

Enregistrer un commentaire