JSON Example With Jersey and Jackson
In this post, we feature a comprehensive Example on JSON With Jersey and Jackson. We are going to see how you can integrate Jesrsey with Jackson to develop JAX-RS RESTful services that produce and consume JSON streams. As you probably know, Jackson is used to marshal a Java Object to JSON, and ummarshal a JSON file (or stream in general) to a Java Object
In this example we are not going to focus on how to create a JAX-RS application from top to bottom. So make sure you read carefully Jersey Hello World Example and pay attention to the sections concerning the creation of the project with Eclipse IDEas well as the deployment of the project in Tomcat.
You can create your own project following the instructions on Jersey Hello World Example. But you can also download the Eclipse project of this tutorial here : JAXRS-HelloWorld.zip, and build your new code on top of that.
1. Project structure
For this example, I’ve created a new Project called “JerseyJSONExample
“. You can see the structure of the NEW project in the image below:
2. Jackson Dependencies
To integrate Jersey with Jackson you have to declare the following dependencies in your pom.xml
file.
JSON/Jackson Dependencies:
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.9</version> </dependency>
This will download jersey-json-1.9.jar
to your local repository along with all the necessary Jackson jars.
So this is the full pom.xml
file of the project:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks.enterprise.rest.jersey</groupId> <artifactId>JerseyJSONExample</artifactId> <version>0.0.1-SNAPSHOT</version> <repositories> <repository> <id>maven2-repository.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> <layout>default</layout> </repository> </repositories> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.9</version> </dependency> </dependencies> </project>
Now, in order for your service to automatically marshal and unmarshal Java Objets to and from Json you have to specify a special parameter to your Jersey serlvet configuration (obviously this will be in the web.xml
file). This parameter is com.sun.jersey.api.json.POJOMappingFeature
and will basically integrate Jersey with Jackson. Here is the updated web.xml
file.
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Restful Web Application</display-name> <servlet> <servlet-name>jersey-XMLExample-serlvet</servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.javacodegeeks.enterprise.rest.jersey</param-value> </init-param> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-XMLExample-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
3. Java class to be represented to JSON
This is the Java class that is going to be represented in JSON format.
Student.java:
package com.javacodegeeks.enterprise.rest.jersey; public class Student { private int id; private String firstName; private String lastName; private int age; // Must have no-argument constructor public Student() { } public Student(String fname, String lname, int age, int id) { this.firstName = fname; this.lastName = lname; this.age = age; this.id = id; } public void setFirstName(String fname) { this.firstName = fname; } public String getFirstName() { return this.firstName; } public void setLastName(String lname) { this.lastName = lname; } public String getLastName() { return this.lastName; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void setId(int id) { this.id = id; } public int getId() { return this.id; } @Override public String toString() { return new StringBuffer(" First Name : ").append(this.firstName) .append(" Last Name : ").append(this.lastName) .append(" Age : ").append(this.age).append(" ID : ") .append(this.id).toString(); } }
4. REST Service to produce JSON output
Let’s see how easy it is with Jersey to produce JSON output using a simple Student
instance.
JerseyClient.java:
package com.javacodegeeks.enterprise.rest.jersey; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/jsonServices") public class JerseyRestService { @GET @Path("/print/{name}") @Produces(MediaType.APPLICATION_JSON) public Student produceJSON( @PathParam("name") String name ) { Student st = new Student(name, "Diaz",22,1); return st; } }
After deploying the application, open your browser and go to:
http://localhost:8080/JerseyJSONExample/rest/jsonServices/print/carlos
This is the response:
Here is the raw HTTP Response:
HTTP Response:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 05 Dec 2013 16:43:08 GMT
{"id":1,"lastName":"Diaz","firstName":"carlos","age":22}
5. REST Service to consume JSON
Here is a REST Service that consumes a simple JSON stream. the JSON object will be parsed and unmarshaled to Student
instance.
JerseyRestService.java:
package com.javacodegeeks.enterprise.rest.jersey; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/jsonServices") public class JerseyRestService { @POST @Path("/send") @Consumes(MediaType.APPLICATION_JSON) public Response consumeJSON( Student student ) { String output = student.toString(); return Response.status(200).entity(output).build(); } }
Now in order to consume that service we have to create a post request and append an XML file to it. For that we are going to use Jersey Client API. To use Jersery Client API you have to add the following dependency in your pom.xml
.
Jesey Client API dependency:
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.9</version> </dependency>
For this, I’ve created a new class, called JerseyClient.java
in a new Package called com.javacodegeeks.enterprise.rest.jersey.jerseyclient
. So the final Project Structure would be like so:
Here is the client:
JerseyClient.java:
package com.javacodegeeks.enterprise.rest.jersey.jerseyclient; import com.javacodegeeks.enterprise.rest.jersey.Student; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; public class JerseyClient { public static void main(String[] args) { try { Student st = new Student("Adriana", "Barrer", 12, 9); ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); WebResource webResource = client .resource("http://localhost:9090/JerseyJSONExample/rest/jsonServices/send"); ClientResponse response = webResource.accept("application/json") .type("application/json").post(ClientResponse.class, st); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } String output = response.getEntity(String.class); System.out.println("Server response .... \n"); System.out.println(output); } catch (Exception e) { e.printStackTrace(); } } }
As you can see, we create a simple Student
instance and send it to the service via a POST Request. This is the output of the above client:
Outptut:
Server response ....
First Name : Adriana Last Name : Barrer Age : 12 ID : 9
Here is the raw POST request:
POST Request:
POST /JerseyJSONExample/rest/jsonServices/send HTTP/1.1
Accept: application/json
Content-Type: application/json
User-Agent: Java/1.7.0_45
Host: localhost:8080
Connection: keep-alive
Content-Length: 59
{"id":9,"firstName":"Adriana","lastName":"Barrer","age":12}
Note: Of course you can produce your POST request using any other tool that does the job. The example will work as long as you append the appropriate code in the POST Request body, like you see in the above request. For instance, you could simply write as a String
in JSON format and append it to the request.
Download Eclipse Project
This was an Example on JSON With Jersey and Jackson. Download the Eclipse Project of this example: JerseyJSONExample.zip