JSON example with Jersey + Jackson

JSON example with Jersey + Jackson


Jersey uses Jackson to convert object to / form JSON. In this tutorial, we show you how to convert a “Track” object into JSON format, and return it back to user.

1. Dependency

To make Jersey support JSON mapping, declares “jersey-json.jar” in Maven pom.xml file.



com.sun.jersey

jersey-server

1.8







com.sun.jersey

jersey-json

1.8



Note

Review the downloaded dependencies in your project classpath, Jackson and related libraries are inlcuded.

2. Integrate JSON with Jersey

In web.xml, declares “com.sun.jersey.api.json.POJOMappingFeature” as “init-param” in Jersey mapped servlet. It will make Jersey support JSON/object mapping.



com.sun.jersey.api.json.POJOMappingFeature

true



File : web.xml - full example.







jersey-serlvet

com.sun.jersey.spi.container.servlet.ServletContainer



com.sun.jersey.config.property.packages

com.mkyong.rest





com.sun.jersey.api.json.POJOMappingFeature

true



1







jersey-serlvet

/rest/*







3. Simple Object

A simple “Track” object, later Jersey will convert it into JSON format.

package com.mkyong;



public class Track {



String title;

String singer;



public String getTitle() {

return title;

}



public void setTitle(String title) {

this.title = title;

}



public String getSinger() {

return singer;

}



public void setSinger(String singer) {

this.singer = singer;

}



@Override

public String toString() {

return "Track [title=" + title + ", singer=" + singer + "]";

}



}

4. JAX-RS with Jersey

Annotate the method with @Produces(MediaType.APPLICATION_JSON). Jersey will use Jackson to handle the JSON conversion automatically.

package com.mkyong.rest;



import javax.ws.rs.Consumes;

import javax.ws.rs.GET;

import javax.ws.rs.POST;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

import javax.ws.rs.core.Response;



import com.mkyong.Track;



@Path("/json/metallica")

public class JSONService {



@GET

@Path("/get")

@Produces(MediaType.APPLICATION_JSON)

public Track getTrackInJSON() {



Track track = new Track();

track.setTitle("Enter Sandman");

track.setSinger("Metallica");



return track;



}



@POST

@Path("/post")

@Consumes(MediaType.APPLICATION_JSON)

public Response createTrackInJSON(Track track) {



String result = "Track saved : " + track;

return Response.status(201).entity(result).build();



}



}

5. Demo

See demo for GET and POST request.

1. GET method

When URI pattern “/json/metallica/get” is requested, the Metallica classic song “Enter Sandman” will be returned in JSON format.

{

"singer":"Metallica",

"title":"Enter Sandman"

}



2. POST method

To test post request, you can create a RESTful client (refer to this Jersey client APIs example), and “post” the json format string to URI pattern “/json/metallica/post“, the posted json string will be converted into “Track” object automatically.

RESTful Java client with Jersey client

This tutorial show you how to use Jersey client APIs to create a RESTful Java client to perform “GET” and “POST” requests to REST service that created in this “Jersey + Json” example.

1. Jersey Client Dependency

To use Jersey client APIs, declares “jersey-client.jar” in your pom.xml file.

File : pom.xml



com.sun.jersey

jersey-client

1.8



2. GET Request

Review last REST service.

@Path("/json/metallica")

public class JSONService {



@GET

@Path("/get")

@Produces(MediaType.APPLICATION_JSON)

public Track getTrackInJSON() {



Track track = new Track();

track.setTitle("Enter Sandman");

track.setSinger("Metallica");



return track;



}

//...

Jersey client to send a “GET” request and print out the returned json data.

package com.mkyong.client;



import com.sun.jersey.api.client.Client;

import com.sun.jersey.api.client.ClientResponse;

import com.sun.jersey.api.client.WebResource;



public class JerseyClientGet {



public static void main(String[] args) {

try {



Client client = Client.create();



WebResource webResource = client

.resource("http://localhost:8080/RESTfulExample/rest/json/metallica/get");



ClientResponse response = webResource.accept("application/json")

.get(ClientResponse.class);



if (response.getStatus() != 200) {

throw new RuntimeException("Failed : HTTP error code : "

+ response.getStatus());

}



String output = response.getEntity(String.class);



System.out.println("Output from Server .... \n");

System.out.println(output);



} catch (Exception e) {



e.printStackTrace();



}



}

}

Output…

Output from Server ....



{"singer":"Metallica","title":"Enter Sandman"}

3. POST Request

Review last REST service.

@Path("/json/metallica")

public class JSONService {



@POST

@Path("/post")

@Consumes(MediaType.APPLICATION_JSON)

public Response createTrackInJSON(Track track) {



String result = "Track saved : " + track;

return Response.status(201).entity(result).build();



}

//...

Jersey client to send a “POST” request, with json data and print out the returned output.

package com.mkyong.client;



import com.sun.jersey.api.client.Client;

import com.sun.jersey.api.client.ClientResponse;

import com.sun.jersey.api.client.WebResource;



public class JerseyClientPost {



public static void main(String[] args) {



try {



Client client = Client.create();



WebResource webResource = client

.resource("http://localhost:8080/RESTfulExample/rest/json/metallica/post");



String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";



ClientResponse response = webResource.type("application/json")

.post(ClientResponse.class, input);



if (response.getStatus() != 201) {

throw new RuntimeException("Failed : HTTP error code : "

+ response.getStatus());

}



System.out.println("Output from Server .... \n");

String output = response.getEntity(String.class);

System.out.println(output);



} catch (Exception e) {



e.printStackTrace();



}



}

}

Output…

Output from Server ....



Track saved : Track [title=Fade To Black, singer=Metallica]