Serialization of Java Objects using Jackson Library

In this post, we will discuss Serialization and deserialization of Java objects of Java objects using Jackson library by converting Java Objects into their JSON representation and then JSON to an equivalent Java object.


 

Nowdays almost all RESTful web services consumes and produces JSON data instead of XML but unfortunately Java SE doesn’t provide any support to convert JSON to Java Object (and vice-versa). But there are many third party libraries available which are very reliable and offers 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. It can also be used 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 few drawbacks of using Jackson library for Data Binding –

  1. It requires the class to have 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, else serialization and deserialization won’t work.
     
  3. Jackson requires Java SE 1.5 or more, so we can’t use it on legacy projects.
     

Java

Download


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]]]

 
Serialization of Java Objects using Google’s GSON Library

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz