Search code examples
javacsvjacksonjackson-dataformat-csv

Parsing CSV into a POJO list with Jackson CSV


I have a string, which contains CSV data and would like to parse this into a list of POJOs.

How can I do this with Jackson CSV?

Bonus: How can I make it so that it uses CSV headers?


My two unsuccessful attempts:

CsvMapper mapper = new CsvMapper();
// First attempt 
CsvSchema schema = mapper.schemaFor(POJO.class); 
// Second attempt
CsvSchema schema =  CsvSchema schema = CsvSchema.emptySchema().withHeader();

System.out.println(schema.usesHeader());
String content = new String(inputFile.getBytes());
MappingIterator<POJO> it = mapper.readerFor(POJO.class).with(schema).readValues(content);

return it.readAll();

The first attempt populated the attributes in a random order which was not the in the order of the CSV columns, or in the order of attributes of the POJO.

The second attempt gave the following error:

Unrecognized field "attribute2" (class uk.ac.packagename.POJO), not marked as ignorable (6 known properties: "attribute2", "attribute3", "attribute4", "attribute5", "attribute6", "attribute1"]) at [Source: java.io.StringReader@617bb5db; line: 2, column: 14] (through reference chain: uk.ac.packagename.POJO["attribute2"])

Solution

  • It turns out that, because my CSV was coming from a MultipartFile as part of a file upload, an invisible character was being added to the front. (don't know why though)

    I fixed this by filtering the raw CSV string for non-alphanumeric characters:

    content.replaceAll("^[\\W]","");
    

    Then the method marked as "Second attempt" worked perfectly.