I have recently upgraded my REST API to use jersey 2.x and now I am unable to retrieve JSON body params the way I used to, the methods simply do not get called anymore. My guess is I'm missing a dependency to parse the JSON to a java object but I'm not too sure what i need to add in, any help appreciated.
pom.xml
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.22</version>
</dependency>
</dependencies>
REST method
@POST
@Path("/users/{userId}/friends")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response followUser(@PathParam("userId") Integer myUserId, FollowUserBean user) {}
FollowUserBean.java
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class FollowUserBean {
public Integer friendId;
public FollowUserBean() {}
}
You need a JSON provider
At time of writing, Jersey 2.x integrates with the following modules to provide JSON support:
Using Jackson
See below the steps required to use Jackson as a JSON provider for Jersey 2.x:
Adding Jackson module dependencies
To use Jackson 2.x as your JSON provider you need to add
jersey-media-json-jackson
module to yourpom.xml
file:To use Jackson 1.x it'll look like:
Registering Jackson module
Besides adding the dependency mentioned above, you need to register
JacksonFeature
(orJackson1Feature
for Jackson 1.x) in yourApplication
/ResourceConfig
subclass:If you don't have an
Application
/ResourceConfig
subclass, you can register theJacksonFeature
in yourweb.xml
deployment descriptor. The specific resource, provider and feature fully-qualified class names can be provided in a comma-separated value ofjersey.config.server.provider.classnames
initialization parameter.The
MessageBodyWriter
provided by Jackson isJacksonJsonProvider
.For more details, check the Jersey documentation about support for common media type representations.
You may be missing Jersey JSON Jackson (2.x) entity providers support module:
It is recommended to use the same Jersey version in all libs.