GWT: Developing in hosted mode with php, json and XAMPP – Part 3

Posted on November 23, 2010


Dealing with json and objects

So, now we have some raw json data back from our server script. How to do something meaningful with it?

The json data that our php script produced is an array of users. To break this down to objects, we can use two entities:

  • User, with properties name and age
  • Users, array of User

Following the GWT Get started Tutorials, we use javascript overlay types for these objects – they are javascript objects, but we interact with them through a java interface. This means that instead of extending the native java types (Object respectively ArrayList), we will use the javascript overlay counterparts:

  • User extends JavaScriptObject
  • Users extends JsArray<User>

So, let’s create those two classes. They’re nothing more than simple value objects, so let’s put them in se.cambiata.gwtphp.client.vo package.
Here’s the code for User:

// User
package se.cambiata.gwtphp.client.vo;
public class User extends JavaScriptObject {
	protected User() {};
	public final native String getName() /*-{ return; }-*/;
	public final native int getAge() /*-{ return this.age; }-*/;	

And here’s the code for Users:

// Users
package se.cambiata.gwtphp.client.vo;
public class Users extends JsArray {
	protected Users() {}
	public static final native Users usersFromJson(String json) /*-{
		return  eval(json);

Now, let’s add some users to our application. In the, after the onModuleLoad() method, add the following code:

	private Users users;

	private void setUsersFromJson(String jsonString) {
		this.users = Users.usersFromJson(jsonString);
		// accessing a user
		User user = this.users.get(1);

This gives us users as a property of the application, and a setter-style method to invoke those users from the json code.
So, let’s feed this setter method with our recieved json.
In the HttpRequestCallback onResponseRecieved method, change the code to include a call to setUsersFromJson — something like this:

					public void onResponseRecieved(Request request, Response response) {
						GWT.log("HttpRequestCallback.onResponseRecieved" + response.getText());

The actual conversion from json to javascript is done in the Users static method usersFromJson, by a simple javascript eval command.
When running this application, the recieved json should be converted into application level Users, and the single users are accessable through

		Users user = this.users.get(index);
Posted in: Uncategorized