Archive
Using Jackson as JSON provider in Jersey 2.x
Using Jackson, a popular JSON parser for Java, in Jersey applications.
When producing and consuming JSON in a Jersey application, will need a JSON provider, otherwise you’ll see an error like this:
A message body writer for Java class ... and MIME media type application/json was not foundAt time of writing, Jersey 2.x integrates with the following modules to provide JSON support:
Among the options mentioned above, I would say Jackson is the one which offers more features when parsing JSON.
Using Jackson #
See below the steps to use Jackson, a popular Java parser for Java, as a JSON provider in 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 the pom.xml file:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.23.1</version>
</dependency>To use Jackson 1.x, add the jersey-media-json-jackson1 artifact to the pom.xml file:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson1</artifactId>
<version>2.23.1</version>
</dependency>Registering Jackson module #
Besides adding the dependency mentioned above, you need to register JacksonFeature (or Jackson1Feature for Jackson 1.x) in your Application / ResourceConfig sub-class:
@ApplicationPath("/api")
public class MyApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(JacksonFeature.class);
return classes;
}
}@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(JacksonFeature.class);
}
}If you don’t have an Application / ResourceConfig sub-class, you can register the JacksonFeature in your web.xml deployment descriptor by adding the feature fully-qualified class name to the jersey.config.server.provider.classnames initialization parameter:
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
</init-param>If you need to register other features, resources or providers, separate their fully-qualified class names with comma (,).
Just in case you are interested in having a look at the implementation, the MessageBodyWriter provided by Jackson is JacksonJsonProvider.
For more details, check the Jersey documentation about support for common media type representations.