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 =
client.resource("http://twittervision.com/user/current_status/bdarfler.json");
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.