Reading CSV with Jackson

“How to use jackson-dataformat-csv”

First there was just JSON

Why and how is CSV different from JSON

Simplest, “untyped” reading of CSV as List<List<String>>

final String CSV_DOC = "1,2,true\n2,9,false\n-13,0,true\n";
final CsvMapper mapper = new CsvMapper();
MappingIterator<List<String>> it = mapper
.with(CsvParser.Feature.WRAP_AS_ARRAY) // !!! IMPORTANT
// If we want them all we use:
List<List<String>> all = it.readAll();
// or if not, we would instead:
while (it.hasNextValue()) {
List<String> row = it.nextValue();
// process

Almost as simple: reading contents as Maps, POJOs

CsvSchema schema = CsvSchema.builder()
MappingIterator<Map<String, String>> it = mapper
// NOTE: no wrapping needed
Map<String, String> row = it.nextValue();
assertEquals("1", map.get("x"));
assertEquals("2", map.get("y"));
assertEquals("true", map.get("visible"));
// CSV module defaults to alphabetic ordering so this is optional:
@JsonPropertyOrder({ "x", "y", "visible" })
public class Point {
public int x, y;
public boolean visible;
MappingIterator<Point> it = mapper
while (it.hasNextValue()) {
Point p = it.nextValue();
int x = p.x;
// do something!
// or, you could alternative slurp 'em all:
List<Point> points = it.readAll();

With a little help from The Header

CsvSchema pointSchema = mapper.schemaFor(Point.class);
CsvSchema headerSchema = CsvSchema.emptySchema().withHeader();
String CSV_WITH_HEADER = ...; // see example above
MappingIterator<Map<String, String>> it = mapper
// and read same as before

And That’s All For Now!

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox