banality — design & communication
Alle Topics anzeigen

Eine etwas andere Sichtweise um eine Serialisierung mit dem Google-Web-Toolkit durchzuführen (Englisch)

Serialisierung von Daten mit dem Google-Web-Toolkit (Englisch)

There are many extensions and even more how-tos and discussions on how to serialize objects when using the Google-Web-Toolkit. The basic question is: How can I use POJOs (Plain-Old-Java-Objects) in my application and pass them to a server (serialize) and how can I convert objects coming from the server (deserialize)?

The most general answer is: Use the great JSON parser and related object types provided by GWT. But this doesn’t solve the problem of having no clue what properties a POJO has. There is no reflection mechanism included and it won’t be in near future. So upon serialization you don’t know what properties an object has und this holds also for deserialization where you don’t know which setters to invoke.

There are many solutions out there but the most require a pre-compilation step where the information about properties is saved to a file (XML, JSON, …). I’m no fan of this solution because it requires you to perform an additional step. There is a simple method where all your data stays in your code. It is not the most beautiful one but it has worked for me in many projects.

So lets take a look at a class that mimics a Person that is serializable:

/**
* Class that mimics a Person.
*
* @author Simon Pamies
*
*/
public class Person extends GWTSerializable {

public static HashMap<String, JSONValue> schema = new HashMap<String, JSONValue>() {{
putAll(GWTSerializable.schema); // "inherit" schema fields

put("forename", new JSONString(""));
put("name", new JSONString(""));
}};

public Person() {
}

public Person(String forename, String name) {
setForename(forename); // use setter
this.set("name", name); // direct access
}

public String getFullName() {
return this.get("forename") + " " + this.get("name");
}

public void setForename(String forename) {
this.set("forename", forename);
}

@Override
public IGWTSerializable copyOf() {
return new Person();
}

@Override
public HashMap<String, JSONValue> schema() {
return schema;
}
}

As you can see here I’m declaring a schema that has typed fields. I do not use POJO properties here but I’m getting the same result and even more: I have a property structure that can be easily reflected and I have a full fledged Java object. The biggest problem here is that you can have typos in attribute names. But this can be solved by introducing constants.

Internetagentur Essen
+49(0)2 01/64 93 24-40
Nachricht schreiben

Internetagentur Bielefeld
+49(0)5 21/7 84 88-27
Nachricht schreiben