Search code examples
javacsvmappingpojo

How to map csv file to pojo class in java


I am using Java Maven plugin. I want to fetch employee.csv file records in POJO class. This POJO class I am generating from employee.csv header and all fields of POJO class are String type. Now I want to map employee.csv to generated POJO class. My requirement is I don't want to specify column names manually because if I change CSV file then again I have to change my code so it should dynamically map with any file, for instance:

firstName,lastName,title,salary
john,karter,manager,54372

I want to map this to POJO which I already have.

public class Employee
{
  private String firstName;
  private String lastName;
  .
  .
  //getters and setters 
  //toString()
}

Solution

  • uniVocity-parsers allows you to map your pojo easily.

    class Employee {
    
        @Trim
        @LowerCase
        @Parsed
        private String firstName;
    
        @Parsed
        private String lastName;
    
        @NullString(nulls = { "?", "-" }) // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
        @Parsed(defaultNullRead = "0") // if a value resolves to null, it will be converted to the String "0".
        private Integer salary; // The attribute name will be matched against the column header in the file automatically.
        ...
    
    }
    

    To parse:

    BeanListProcessor<Employee> rowProcessor = new BeanListProcessor<Employee>(Employee.class);
    
    CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.setRowProcessor(rowProcessor);
    parserSettings.setHeaderExtractionEnabled(true);
    
    CsvParser parser = new CsvParser(parserSettings);
    
    //And parse!
    //this submits all rows parsed from the input to the BeanListProcessor
    parser.parse(new FileReader(new File("/path/to/your.csv"))); 
    
    List<Employee> beans = rowProcessor.getBeans();
    

    Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).