Skip to content

Chapter Intro Beyond JSON

Tatu Saloranta edited this page Sep 7, 2016 · 4 revisions

Jackson Manual: Introduction - Beyond JSON

As briefly mentioned earlier, Jackson suite also offers other backends (called "dataformat modules", or "dataformats" for short): while JSON was the first backend implemented, it has not been the only one for years now.

We will look into the full(er) list of existing dataformat modules, but let's show case couple of backends to now give an idea of both usage, and possibilities this opens.

Reading XML

To read and write XML data, you will need to use a XmlMapper -- a sub-class of ObjectMapper -- for all access. But this is about the only immediately obvious difference. Using the Point class definition we saw earlier on, expected XML format could look like this: (*)

<point>
  <x>1</x>
  <y>4</y>
  <z>6</z>
</point>

or:

<point x="1" y="4" z="6" />

and reading code would look like:

XmlMapper xmlMapper = new XmlMapper();
Point p = xmlMapper.readValue(new File("coord.xml"), Point.class);

Code to write out XML in same format is left (for now!) as an exercise to the reader.

(*) one way to see what expected structure would look like you can try constructing object instance and writing it out -- Jackson focuses on making sure that it can read back what it writes -- and this lets you see if there are unexpected differences between structure you have, and output you got.

Writing CSV

CSV as a format needs little bit more work than JSON or XML because of its nature: it is a positional tabular data format. To map data between CSV dataset and Java Objects, there is need to Map contents of columns (identified by column number) to logical names of properties (*). This mapping is specified by defining a CsvSchema (which is a subtype of FormatSchema, instances of which are used with all schema-based formats): for now we can think of CsvSchema as a simple mapping form logical property names to and from column position (index), needed for databinding.

So to write a CSV file we could use code like

CsvSchema schema = CsvSchema.builder()
  .addColumn("x")
  .addColumn("y")
  .addColumn("z")
  .setUseHeader(true) // yes, write header line
  .setColumnSeparator(',') // this is the default so could leave out
  .build();
CsvMapper csvMapper = new CsvMapper();
SequenceWriter w = csvMapper.writerFor(Point.class)
  .writeValues(new File("data.csv"));
w.write(new Point(1, 0, 2));
w.write(new Point(2, 1, 3));
w.write(new Point(0, 3, 1));
w.close();

and we would get file data.csv with contents like:

x,y,z
1,0,2
2,1,3
0,3,1

And for sake of completeness, we could even just read the contents back in like so:

List<Point> points = csvMapper
  .readerFor(Point.class)
  .readValues(new File("data.csv"))
  .readAll();

(*) or not: there is a way to also expose data in "raw" or "untyped" way; more on this in a later Chapter.