How to implement RESTful JSON Web Services in Java

You can implement RESTful Web Services in Java using the JAX-RS framework.

JAX-RS is part of the JavaEE 6 platform. But if you are not using a JavaEE 6 application server, you can use the reference implementation Jersey and embed it in any web application server.

However, it’s quite awkward to produce JSON output from Jersey.

Jersey has some support for producing JSON via JAXB, but to get the NATURAL encoding (which you probably want) you need JAXB 2.1. And that can be problematic since JAXB 2.0 is bundled with JavaSE 6 and with some application servers (such as WebLogic). Overriding that with a later version of JAXB can be really difficult. Using JAXB is also a bit clumsy if you only want to produce JSON.

And using the low-level JSON support in Jersey is not fun at all.

The solution is to use Jackson and refer to its JAX-RS integration package org.codehaus.jackson.jaxrs in Jerseys com.sun.jersey.config.property.packages parameter (remember to separate several packages with semicolon ; ).

Then just return POJO:s from your JAX-RS resource classes.

You need these dependencies:

	<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-core</artifactId>
		<version>1.1.4.1</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-core-asl</artifactId>
		<version>1.2.1</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.2.1</version>
	</dependency>
	        <dependency>
	        <groupId>org.codehaus.jackson</groupId>
	        <artifactId>jackson-jaxrs</artifactId>
	        <version>1.2.1</version>
	</dependency>
This entry was posted in AJAX, Java, JavaEE, web. Bookmark the permalink.

One Response to How to implement RESTful JSON Web Services in Java

  1. Nemanja says:

    Hey man thank you for this post.

    I’ve included jackson dependencies, binded JacksonJsonProvider to Reader and Writer in guice and I actually thought it had worked. Only later when I was developing Android client and run into “List with one element” problem have I learnt that I’m actually not using Jackson. This post helped me to switch it on.

    Thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *



(this is a captcha)