Jackson – Java to JSON and JSON to Java

Jackson – Java to JSON

Jackson provides classes that can be used to convert a Java Object to JSON and back. In this example, we look at how to convert Java to JSON and JSON to Java. We will start with a simple class and gradually start adding complexities to it. Let’s say that we are a music company and we want to publish an API where users can query for Album. We first build an Album class with a single property title.

Java to JSON and JSON to Java using ObjectMapper

we use the ObjectMapper to convert the Object to JSON. By Default Jackson would use BeanSerializer to serialize the POJO. Here’s how our serializer Example looks so far. Note that the bean should have getters for private properties or the property should be public Here’s how the JSON looks

Lets add an array of links to the album (along with their getters and setters) These could be links to the press releases or album reviews.

In the main method add this:

This is how the JSON looks now. Note that the array is converted to a JSON array. (enclosed within ‘[‘ and ‘]’)

Next we add a List of Songs to the Album.

Add the list to the Albums Object

The resulting json looks like this. Note that the List is also converted to an array. You can learn more about List Serialization in
this
tutorial.

Next, lets add an artist to the Album. Artist is a class that contains the artist name and his birthdate represented by a Date instance. Note that Artist is an object and hence is enclosed in JSON by ‘{‘ and ‘}’. These brackers are JSON representation of objects and contains key value pairs. For brevity we declare the Artist properties as public.

Lets add an Artist to the album

The JSON

To make JSON visually more readable we add this line. Note that this should not be done for production systems, but only during testing or development since this would increase the size of the json.

The JSON now looks well formatted

we now add a map of musicians and the instrument they play in the album.

and in the main class

The json

Lets add some more features to the conversion. we first tell the mapper to arrange the Map by keys using it natural order

The date has been formatted as the epoch time. Lets format it into a more human readable format

By default, jackson uses the name of the java field as the name of the json property. You can change that by using annotations as explained in this tutorial. However at times you may not have access to the java bean or you do not want to bind the java bean to a Jackson annotation. In this case jackson provides a way to change the default field name. Use the setPropertyNamingStrategy method on the mapper to set the naming strategy for the field. You need to override either the the nameForField method or the
nameForGetterMethod depending on whether you have public field in the bean or a getter in the bean. In our example lets change the ‘title’ of the album to ‘Album-Title’ and the ‘name’ of the artist to ‘Artist-Name’. Make this changes to the main method

The json now looks like this

Let us now see how Jackson handles null. we add three new properties to the Artist class and do not assign values to them. we add age(int), homeTown(String) and awardsWon (String[])

Here’s how they look after converting to json

we use this configuration to ignore properties that are empty

To explicitely ignore a field use filters as described in this tutorial. Here’s the complete example

This is the first part of the tutorial where we saw how to convert a java object to json. in the next part we see how to build a JSON using a tree approach.

Java to JSON and JSON to Java using Tree Model

It is also possible to build a json using a simple tree model. This could be useful if you dont want to write classes for your JSON structure. We will use the same example as above i.e. an album that has an array songs, an artist and an array of musicians. To write a tree you need to first do this setup:

  • Create a JsonNodeFactory to create the nodes
  • Create a JsonGenerator from a JsonFactory and specify the output method. In this method we print to console.
  • Create an ObjectMapper that will use the jsonGenerator and the root node to create the JSON.

After setting it all up we create a single root node for album. Note that by default the object mapper does not name the root node.

This prints

A lot of lines of code to print two brackets! but lets see how it is to build our json now. We first add the first property of the album i.e. ‘Album-Title’.

This is how our JSON looks now

We now add the links array

The JSON

Next we add the artist object. Note that artist by itself is a JsonObject. we add that to the album.

The JSON

We not add the musicians. The musicians are not in an array but there is an object of type musicians. We therefore create an object.

The JSON

You can similarly add other elements. If you have multiple albums then you would probably generate an array in a for loop. It would typically be faster to generate JSON from a Java Object.

Jackson – Creating JSON Stream

Look at this tutorial to see an example of generating a JSON stream.

Leave a Reply

Your email address will not be published. Required fields are marked *