I am trying to create a restful-jersey webservice. I have to pass JSON object to the webservice.
@POST
@Path("/saveVehicleTrackingData")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String saveVehicleTrackingData(VehicleTracking vehicleTracking) {
return vehicleTracking.toString();
}
The only thing that I did to add json provider to my project is I added this maven dependency :
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.1</version>
</dependency>
As this page says :
Due to auto-registration, it should be possible to simply add Maven
dependency (or include jar if using other build systems) and let JAX-RS
implementation discover provider. If this does not work you need to consult
documentation of the JAX-RS implementation for details.
But auto registration is not working and I am getting 415-Unsupported Media Type error when trying to access the web-service. Is there any guide available on how to register json provider properly?
For "auto-registration" to work, the app needs to be configured to scan the entire classpath. This may be not be optimal, and most examples won't even mention how to do this. But one way, is to not have a web.xml and use an empty Application
subclass with the @ApplicationPath
annotation.
@ApplicationPath("/api")
public class JerseyConfig extends Application {}
This would be enough to enable classpath scanning. There maybe other ways, but normally what you will see used is package scanning. In you web.xml, you might see something like
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>your.package.to.scan</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
This scans your.package.to.scan
package. If you want it to scan for the Jackson classes, you can add the package in the list, i.e.
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.package.to.scan,
com.fasterxml.jackson.jaxrs.json
</param-value>
If you are using an ResourceConfig
subclass, you can register(JacksonJsonProvider.class)
or register(JacksonJaxbJsonProvider.class)
for JAXB annotation support.
If you are using an Application
subclass, you can add an instance of the provider in your overridden getSingletons()
method.
As an aside, if you are using Jersey 2.9+, you can just use this dependency
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
and without any other configuration, it will be automatically register. This dependency, actually, uses the dependency you mentioned in your post, but uses a Jersey specific Auto Discoverable feature to register it.