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.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Jakub Podlesak

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today