REST calls and JSON results in Java

I recently had the need interact with Twittervision’s RESTful api from Java. As usual, I started googling around for a solution but nothing obviously stood out. There are a handful of RESTful java frameworks, but these focus on providing a RESTful api and not consuming one. Finally, after an annoyingly difficult search I found an impressively simple solution based on Jersey.

The point to realize is that Jersey provides both a sever and a client api. To make use of the client api requires three simple lines:

Client client = Client.create();
WebResource webResource = 
String response = webResource.get(String.class);

The result is a string of JSON, but now, how to parse it. After searching around I ended up settling on json-simple. A few simple lines of code and we can get the address for any twitter user.

final JSONObject jsonObj = (JSONObject) JSON_PARSER.parse( response );
if ( jsonObj != null && jsonObj.containsKey( "location" ) )
final JSONObject location = (JSONObject) jsonObj.get( "location" );
return location.get( "address" ).toString();

So, once again, simple stuff but not as obvious as I was hoping it would be.

About these ads

About Benjamin Darfler
Coder, Meditator, Photographer

8 Responses to REST calls and JSON results in Java

  1. Pingback: AMIS Technology blog » Blog Archive » Leveraging RESTful Services from Java application using Jersey (Introduction)

  2. unknown says:

    final JSONObject jsonObj = (JSONObject) JSON_PARSER.parse( response)

    JSON_PARSER not available in json-simple.jar…Can you please try this ?

  3. unknown says:

    It’s working fine…The below is the correct one…
    JSONParser parser=new JSONParser();

  4. thanks mate, this was very useful!

  5. Alion says:

    Line with & & it’s not working :(

  6. Benjamin Ndugga says:

    Hi Can we have the JSON Libraries added for download

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: