Tuesday, January 4, 2011

Add JSON Support to your REST Service

Continuing from my previous post about a standalone unit-test mechanism for your RESTful service, now I'll add JSON support to that service, which already gives you XML. This turns out to be a pretty simple thing - all we need is:

  1. Tell the RESTful service to produce both XML and JSON
  2. Add the runtime dependency you'll need 
  3. Add some tests to confirm things


Configuring the RESTful service to produce both XML and JSON involves adding this annotation to your interface (or to the concrete class):


@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Using Apache CXF, we'll need the jettison jar at runtime:


<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.2</version>
</dependency>

That's actually all I had to do. My new unit tests confirm things for me - I'm using the same standalone server approach as outlined in my previous post, and I'm assuming in the following tests that certain strings are contained in the response:


@Test(enabled = true)
public void confirmXmlServices() throws Exception {
assert confirmResponse("http://localhost:9000/info", true, "<info") == 200;
}

@Test(enabled = true)
public void confirmJsonServices() throws Exception {
assert confirmResponse("http://localhost:9000/info", false, "{\"info\":{") == 200;
}

private int confirmResponse(String url, boolean isXml, String expectedInResponse) throws Exception {

HttpClient httpclient = new HttpClient();
GetMethod get = new GetMethod(url);
get.addRequestHeader("Accept", isXml? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON);
httpclient = new HttpClient();
try {
int status = httpclient.executeMethod(get);
String response = get.getResponseBodyAsString();
assert response.contains(expectedInResponse);
return status;
} finally {
get.releaseConnection();
}
}

Again, my thanks to the Apache CXF samples, from which again I've gratuitously lifted and modified.

No comments:

Post a Comment