Monday, February 1, 2010

GWT + JSON

Hi all,

I had an opportunity to use JSON with GWT and I would like to share the implementation idea.

I take username from the username field in the GWT client page and create a JSON object to be passed to the server. Following is the client side code to create the JSON object

private String createJSONPojo(String userName)
    {
        JSONObject ob = new JSONObject();
        JSONString uname = new JSONString(userName);
        ob.put("userName", uname);
        return ob.toString();
    }

The JSON object being used in the above case is from the com.google.gwt.json.client package of gwt-user.jar i.e there is JSON support in GWT.

Now the question comes how do I decode the JSON Object string at the server side. I used an external json support library at the server side. Of course we can use the client side library itself at the server side too but I wanted to avoid getting any client side code/jars to server side. The external library used was json-lib-2.2.2-jdk15.jar. Following is the code to interpret the JSON string at the server side.

public String createUserJSON(String json)
    {
        JSONObject ob = JSONObject.fromObject(json);
        UserPojo pojo = new UserPojo ();
        pojo.setUserName(ob.getString("userName"));
        userservice.createUser(pojo);
        return "success";
    }

The library provides methods to create JSON Objects on server side and send them to the client. Similarly the GWT library has a JSONParser class to parse the JSON string at the client side.