X
  • REST
    August 7, 2007

JSON Entity Providers In Jersey

I have recently added support for JSON entity providers to Jersey. Here you can find a simple sample showing how to utilize them.
The entity providers follow a general schema described by Paul.
The following resource class will publish CZK exchange rates for EUR and USD. Data will
be provided in JSON format.
@UriTemplate("/rates")
public class ExchangeRates {
@ProduceMime("application/json")
@UriTemplate("CZK")
public JSONObject getRates() {
try {
return new JSONObject()
.put("EUR", 28.08)
.put("USD", 20.04);
} catch (JSONException ex) {
throw new WebApplicationException(ex);
}
}
}

After deploying the resource and sending a GET request to http://<host>:<port>/rates/CZK
the following data will be provided to you:
{"EUR":28.08,"USD":20.04}

You might of course want to cover multiple currencies.
Following sample code shows how to achieve it.
@UriTemplate("/rates")
public class HelloWorldResource {
@HttpMethod("GET")
@ProduceMime("application/json")
@UriTemplate("{currency}")
public JSONObject getRates(@UriParam("currency") String currency) {
if ("CZK".equals(currency)) {
try {
return new JSONObject()
.put("EUR", 28.08)
.put("USD", 20.04);
} catch (JSONException ex) {
throw new WebApplicationException(ex);
}
} else throw new NotFoundException("Unknown currency " + currency);
}
}

This way you do not need to hardcode specific currency to the URI template.
In a real web service you would probably return data taken from a database.
However the samples shown the way to use JSON format for data transport from
a Jersey based web service to it's client.

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.