Missing Jackson CSV Columns

I am using Jackson CSV to parse a CSV file in POJO. My problem is that if there are too few columns in the CSV row, the parser does not complain and simply sets the remaining fields to null.

Code Analysis:

CsvMapper csvMapper = new CsvMapper(); csvMapper.addMixInAnnotations(Person.class, PersonCsvMixin.class); CsvSchema schema = csvMapper.schemaFor(Person.class).withHeader(); MappingIterator<Person> it = csvMapper.reader(dataClass).with(schema).readValues(csv); LinkedList<Person> output = new LinkedList<>(); while(it.hasNext()) { output.push(it.next()); } 

Mixin:

 import com.fasterxml.jackson.annotation.*; @JsonPropertyOrder(value = { "FirstName", "LastName", "Title"}) public abstract class Person { @JsonProperty("LastName") public abstract String getLastName(); @JsonProperty("FirstName") public abstract String getFirstName(); @JsonProperty("Title") public abstract String getTitle(); } 

Data class:

 public class OfficespaceInputEmployee implements Serializable{ protected String firstName; protected String lastName; protected String title; // .. getters and setters } 

If I parse the file as shown below, there are no errors, even if two fields are missing in the middle record. Instead, LastName and Title become null

 "FirstName", "LastName", "Title" "John", "Smith", "Mr" "Mary" "Peter", "Jones", "Dr" 

Is it possible to enable a function that will lead to an error?

+5
source share
2 answers

You can make an exception yourself when you create a LinkedList output inside a while loop:

 while(it.hasNext()) { Person line = it.next(); //call a method which checks that all values have been set if (thatMethodReturnsTrue){ output.push(line); } else{ throw SomeException(); } } 
+3
source

I would suggest registering an RFE for problem tracking, for something like CsvParser.Feature.REQUIRE_ALL_COLUMNS : if enabled, the parser will throw an exception indicating that one or more expected columns are missing. This sounds like a helpful addition to me.

+2
source