Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

REST services are great, JSON is great, not having to do any manual conversion between POJOs and JSON is even better. Here's how you do that with Jersey.

If you haven't read it, check out my previous article about Using Jersey 2.x as a shared library on WebLogic 12.1.2. If you're not using WebLogic 12.1.2 or Jersey as a shared library, this article is still relevant but you'll have to take care of your own service packaging.

First add Jackson as a dependency to your Maven POM.
 pom.xml
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
<scope>compile</scope>
</dependency>


Then in your application class (the one that extends ResourceConfig) make sure to register the JacksonFeature class. If you're not familiar with the Jersey application model, read about it here.
 REST Application
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(JacksonFeature.class);
...
}
}


Finally in your resource (the class annotated with @Path, as described here) add @Produces annotation with MediaType.APPLICATION_JSON as the parameter. This tells Jersey that your resource will produce JSON output. The annotation can be either on the resource class itself, or any of the methods that are required to produce JSON output.



All you then have to do is add a return type to your resource method. In my particular case I used a Map, as below:
 REST Service Resource
@Produces(MediaType.APPLICATION_JSON)
@Path("myresource")
public class MyResource {
@GET
@Path("test")
public Map<String, String> testMap() {
Map<String, String> myMap = new HashMap<>();
/* code to populate the map */
return myMap;
}


The output generated becomes something like this:
 JSON Output
{
"key1": "value1",
"key2": "value2"
}


As you notice there is no code to manually convert my Map to JSON. The JacksonFeature that was registered earlier takes care of all of that automatically for you. Of course, you don't have to use Map as I did, any POJO will work.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.