Marshalling Java to JSON, never be hard anymore!

Thanks to Jackson Feature in Jersey

Learn on Udemy Today!


When you write a web service in Java, you might have faced lot of struggle to convert the Java object into JSON. This will never be a hard task anymore after you go through this article.

In our previous article, we have seen how easy to start writing web service in Java. I recommend you to read the article first before we move further.

We cannot expect such a simple example when we implement features in the real world. This post will take you to the advanced concepts in a easiest way. We are going to expose 2 resource methods /books and /books/{id} in-order to fetch list of books and a book by the given id respectively. To achieve this we have to do the following steps…

  • Introduce bean class with JAXB annotation
  • Introduce for getting dummy data
  • Add 2 methods in to handle /books and /books/{id} resources
  • Change the pom.xml to enable the Jackson media type support
  • Introduce for enabling the JacksonFeature (Java serialization purpose)
  • Register RestSkolApplication class file into web.xml

@XmlRootElement and @XmlElement annotations are taken from JAXB. Jersey framework uses JAXB annotation for generating JSON output.

NOTE: is a dummy data provider. Data will be fetched from database in real world.


  • getAllBooks() – Fetch all the available books and return JSON array as response
  • getBook(String id) – Fetch a book object by the given id and return JSON object

pom.xml changes:

Next we have to add the Jackson media type support for our project. To achieve this, we need to add the following dependency in our pom.xml file

NOTE: Java to JSON marshalling will be handled by the JacksonFeature support which is registered into our application.

web.xml changes:

NOTE: Watch out for the init-param changes where the RestSkolApplication has been registered


All our code changes are done. Package and deploy the application to see the changes. When you access the application, you can see the following output.


[{“id”:”1″,”title”:”The Lean Startup”,”isbn”:”0670921602″,”author”:”Eric Ries”},{“id”:”2″,”title”:”Zero to one”,”isbn”:”0753555190″,”author”:”Peter Thiel”},{“id”:”3″,”title”:”The 100$ Start-up”,”isbn”:”023076651X”,”author”:”Chris Guillebeau”}]


{“id”:”1″,”title”:”The Lean Startup”,”isbn”:”0670921602″,”author”:”Eric Ries”}

I believe that, you have enjoyed the article. Thanks to Jackson feature for making our job easy for marshalling Java to JSON object without any hand-written serialization code.

Read also,

Please subscribe to our newsletter for our latest update directly to your inbox. Share the joy of reading with your friends!