Friday, September 7, 2007

Accelerating AJAX based Web Client Development with JSON and GWT

With the rise of Web 2.0, web client are doing more than parsing and displaying HTML. Web Client are powerful than ever before. There is a shift in programming paradigm with servers providing services and serving data and Clients parsing data, managing state information over and above powerful AJAX UIs. Servers are now proposed to be built the REST way. Server may return data in different format. AJAX has been associated with XML response but response can be in any format. One such format which makes Web 2.0 client development really easy is JSON.

JSON is very similar to XML. It is also text based. Server side objects can be easily serialized into JSON text format using frameworks like TurboGears.

For example, a library application might provide a Web service that yields books in this XML format:


<book>
  <author>
     <fullname>Vishal Jain</fullname>
     <org>Consulting</org>
  </author>
  <chapters>
     <chapter page="'10'">Chapter 1</chapter>
     <chapter page="'20'">Chapter 2</chapter>
  </chapters>
</book>

With JSON, it looks like this:


{
   "author" : {
   "fullname": { "value" : "Vishal Jain" } ,
   "org": { "value" : "Consulting" }
   }
   "chapters": {
      "chapter" : [
        { "page" : "10", "value" : "Chapter 1" } ,
        { "page" : "20" , "value" : "Chapter 2" }
      ]
   }
}

Working with JSON is Javascipt is very easier. In Javascript, we can access information about chapter 2 as

var book = eval('(' + req.responseText + ')');
inputBox.value = book.chapters.chapter[1].value;

An example of JSON response from a real world service can be seen here.
http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=potato&results=2&output=json

Working with JSON using GWT

GWT provides an elegant way of client side programming where developer codes in Java and Java code is converted into Javascript by GWT.

GWT comes with API which make working with JSON easier.

A typical cycle will include:

  • Sending HTTP GET/POST request for JSON response.
  • Parsing JSON response in Response Handler
  • Extracting Data and displaying it as appropriate.
Lets take them one by one.

Sending HTTP GET/POST request for JSON response

HTTPRequest.asyncGet(, new JSONResponseTextHandler())

Parsing JSON response in Response Handler

Implement a response handler extending ResponseTextHandler

private class JSONResponseTextHandler implements ResponseTextHandler {
    public void onCompletion(String responseText) {
      try {
        JSONValue jsonValue = JSONParser.parse(responseText);
        displayJSONObject(jsonValue);
      } catch (JSONException e) {
        ...
      }
   }
}

Extracting Data and displaying it as appropriate

  private void displayJSONObject(JSONValue jsonValue) {
    JSONObject book;
    
    if ((book = jsonValue.isObject()) != null) {
        JSONValue chapters = book.get("chapters");
        if(chapters != null) {
            JSONArray chapterArray;
            if ((chapterArray = chapters.isArray()) != null) {
                JSONObject chapter = chapterArray.get(1).isObject();
                inputBox.setText(chapter.get("value"));
            }
        }
    }
}

That's it!!!

A demo of JSON/GWT is available here.

The source of this demo comes bundled with Google Web Toolkit.

No comments: