Marianne Plays With Computers

My Digital Adventures

JSON with Jackson – Old School — July 4, 2015

JSON with Jackson – Old School

I needed to construct and read some JSON data, and Jackson happened to be the tool that was on hand. I later found out that it wasn’t the latest version, though. We have been using it for a while, so the version we have is 1.9, and a non-backwards compatible version 2 had subsequently come out. For extra fun, the repository that had hosted the Jackson project and its archived shut down forever right in the middle of my project. So when I wanted to reference the javadocs, Google mostly wanted to send me to the now-defunct site. I did finally manage to find a zip file of them to download to my PC here.

So if you’re also kickin’ it old school with Jackson, it doesn’t have the most intuitive interface, but once you get used to it, it’s not difficult to use it to create and read JSON.

To create JSON content, start with a JsonFactory:

JsonFactory factory = new JsonFactory();

Use the factory to create a JsonGenerator:

JsonGenerator generator = factory.createJsonGenerator(outputStreamOrWriterOrFile);

Use the write* methods on the generator to create JSON:

generator.writeStartObject();
generator.writeStringField("name", "field");
generator.writeNumberField("value", 42);
generator.writeArrayFieldStart("myArray");
generator.writeString("item1");
generator.writeString("item2");
generator.writeEndArray();
generator.writeEndObject();

And don’t forget to close when you’re done (ask me how I knew that!):

generator.close();

You can then take the OutputStream, Writer, or File and use it to do stuff with your JSON.

By the way, the code above should produce this JSON:

{"name":"field","value":42,"myArray":["item1","item2"]}

Advertisements