How to easily process CSV file to List<MyClass>

user3279067 picture user3279067 · Mar 18, 2014 · Viewed 8.7k times · Source

In my application I use a lot of CSV files which I have to read and build a lists based on them. I'd like to discover an easy way to do this. Do you know any easy framework which does it without using number of config files etc?

For instance, I have got a class Person:

public class Person {
    String name;
    String surname;

    double shoeSize;
    boolean sex; // true: male, false:female

    public Person() {
    }

    public String getName() {
            return name;
    }

    public void setName(String name) {
            this.name = name;
    }

    public String getSurname() {
            return surname;
    }

    public void setSurname(String surname) {
            this.surname = surname;
    }

    public double getShoeSize() {
            return shoeSize;
    }

    public void setShoeSize(double shoeSize) {
            this.shoeSize = shoeSize;
    }

    public boolean isSe) {
            return sex;
    }

    public void setSeboolean sex) {
            this.sex = sex;
    }

}

For this class, I have prepared CSV file:

name,surname,shoesize,sex
Tom,Tommy,32,true
Anna,Anny,27,false

How can I do it easily?

Answer

Asaf picture Asaf · Mar 20, 2014

One of the simplest ways to read and serialize data is by using the Jackson library. It also has an extension for CSV, you can find the wiki here

Let's say you have a Pojo like this:

@JsonPropertyOrder({ "name", "surname", "shoesize", "gender" })
public class Person {

    public String name;
    public String surname;
    public int shoesize;
    public String gender;

}

And a CSV like this:

Tom,Tommy,32,m
Anna,Anny,27,f

Then reading it is done like so:

MappingIterator<Person> personIter = new CsvMapper().readerWithTypedSchemaFor(Person.class).readValues(csvFile);
List<Person> people = personIter.readAll();

This is simple enough for my taste, basically all you need to do is add the column order in your CSV file using the @JsonPropertyOrder annotation and then just read the file using the above 2 lines.