GWT, JSON and REST

This week’s post is about integrating JSON with GWT. GWT allows you to create a data object that represents the underlying JSON object. They call this an overlay. Any class that exends JavaScriptObject can be used as an overlay. For example, this snippet of a User object will be used by GWT to handle received JSON data. Notice that the getters and setters are declared as native methods and there are no class variables declared for the setters. That allows the GTW compiler to compile the class into Javascript and access the underlying JSON object.


public class UserDO extends JavaScriptObject {

protected UserDO() {
}

public final native int getId() /*-{
return id;
}-*/;

public final native void setId(int id) /*-{
this.id = id;
}-*/;

public final native String getHash() /*-{
return hash;
}-*/;

public final native void setHash(String hash) /*-{
this.hash = hash;
}-*/;

public final native String getEmail() /*-{
return email;
}-*/;

public final native void setEmail(String email) /*-{
this.email = email;
}-*/;
...

Here’s an example of using the DTO above. Notice there is no constructor declared in the class, but it is created by calling createObject(). GWT uses that call to set up the underlying JSON object. Once it’s created the class can be used like any other object.


UserDO dto = (UserDO) UserDO.createObject();
dto.setEmail(user.getText());
dto.setPassword(password.getText());
...

Sending the DTO as the message body simply requires stringifying the object to JSON and setting the appropriate header.


public static void sendPost(String path, JavaScriptObject msg, RequestCallback callback){
try {
StringBuffer url = new StringBuffer(baseUrl);
url.append('/').append(path);

RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url.toString());
String requestData = null;
if(msg != null){
builder.setHeader("Content-Type", "application/json");
requestData = JsonUtils.stringify(msg);
}
Request request = builder.sendRequest(requestData, callback);
} catch (RequestException e) {
GWT.log("Couldn't retrieve JSON");
}
...

Once the request is received by the server, the server responds to the RequestCallback passed in from above. In this example, a completed UserDO object is returned by the server. We can deserialize it into a UserDO object and use it as an object.


public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
UserDO responseDto = JsonUtils.safeEval(response.getText());
...

That’s it for this week, hope that’s helpful to someone. This process can be tricky, and the GWT docs, while good, don’t explain all the details for this.