Wednesday, September 15, 2010

GWT and Grails (II) with JSON

The previous post http://gwtgrails.blogspot.com/ demonstrated GWT insteracting with server service provided by Grails.

This post demonstrates how to access JSON data source. I will use grails to render a JSON response for demonstration purpose. The code is just to demonstrate how GWT access JSON and use the data, not trying to make the code to solve actual computing problem correctly.

1. Prepare JSON data source
a. grails create-domain-class Stock
This create the Stock.java class
b. add variables to Stock.java
class Stock {
String name;
String symbol;
Double price;
long id;
}

2. create controller
a. grails create-controller jsondemo
This create
grails-app/controllers/grailsgwtdemo/JsondemoController.groovy
b. add method to render a JSON

import grails.converters.JSON;
class JsondemoController {

def index = { }
def stocks={
List results=new ArrayList()
(0..10).each{
def data=new Stock()
data.id=it
data.symbol="s"+it
data.name="name"+it
data.price=it
results.add(data)
}
render results as JSON
}
}

3. Test json data source is working:
a. start grails
grails run-app
b. run url: http://localhost:8080/grailsgwtdemo/jsondemo/stocks

4. Access json from client client.java

a. Add a class src/gwt/com/demo/client/StockData.java

package com.demo.client;

import com.google.gwt.core.client.JavaScriptObject;

class StockData extends JavaScriptObject { // [1]
// Overlay types always have protected, zero argument constructors.
protected StockData() {} // [2]

// // JSNI methods to get stock data.
public final native String getSymbol() /*-{ return this.symbol; }-*/; // [3]
public final native double getPrice() /*-{ return this.price; }-*/;
public final native String getName() /*-{ return this.name; }-*/;

// // Non-JSNI method to return change percentage. // [4]
public final double getChangePercent() {
return 100.0 *0.5/getPrice();
}
}

This way, the code looks like pure java.

b. add these to the client.java

import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;

private static final String JSON_URL = "http://localhost:8080/grailsgwtdemo2/jsondemo/stocks";

String url = URL.encode(JSON_URL);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
displayError("Couldn't retrieve JSON"+exception.toString());
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
updateTable(asArrayOfStockData(response.getText()));
} else {
displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
}
}
});
} catch (RequestException e) {
displayError("Couldn't retrieve JSON:"+e.toString());
}
}

/*
* Convert the string of JSON into JavaScript object.
*/
private final native JsArray asArrayOfStockData(String json) /*-{
return eval(json);
}-*/;

/**
** Update the Price and Change fields for all rows in the stock table.
**
** @param prices Stock data for all rows.
**/
private void updateTable(JsArray prices) {
for (int i = 0; i <>
updateTable(prices.get(i));
}

lastUpdatedLabel.setText("total num of stocks returned : "+prices.length());
}
private void displayError(String error) {
errorMsgLabel.setText("Error: " + error);
errorMsgLabel.setVisible(true);
}
private void updateTable(StockData price) {
stockLabel.setText(stockLabel.getText()+":"+price.getSymbol());
}

Follow:
http://code.google.com/webtoolkit/doc/latest/tutorial/JSON.html

No comments:

Post a Comment