This post will discuss the serialization and deserialization of Java objects using the Jackson library by converting Java objects into their JSON representation and then JSON to an equivalent Java object.

Nowadays, almost all RESTful web services consume and produce JSON data instead of XML. Unfortunately, Java SE doesn’t support converting JSON to Java Object (and vice-versa). But there are many third-party libraries available that are very reliable and offer high performance. One such library is Jackson.

Jackson is a multi-purpose, high-performance Java library for processing JSON. It provides Data Binding functionality that can be used to convert Java objects into their JSON representation. We can also use it to convert a JSON string to an equivalent Java object.

Jackson org.codehaus.jackson.map.ObjectMapper has writeValueAsString() and readValue() methods to convert Java objects to JSON string and vice-versa.

But before we use it, we want to list out a few drawbacks of using the Jackson library for Data Binding:

  1. It requires the class to have a default no-args constructor to instantiate Java Object from JSON string. If no-args constructor is not provided, it will throw JsonMappingException.
  2. Unlike Gson, Jackson will require getters for all private fields, otherwise serialization and deserialization won’t work.
  3. Jackson requires Java SE 1.5 or more, so we can’t use it on legacy projects.

The following program demonstrates it:

Download Code

Output:

Converting Person object to JSON string:
{"name":"Jon Snow","age":22,"student":{"id":"Jon_Snow_22","subjects":["Maths","Science"]}}
 
Converting JSON string to Person object:
[Jon Snow, 22, [Jon_Snow_22, [Maths, Science]]]

That’s all about serialization of Java objects using Jackson Library.

 
Also See:

Serialization of Java objects using Google’s Gson library

 
Useful JSON Tools: