Json Java serialization that works with GWT [closed]

Take a look at GWT’s Overlay Types. I think this is by far the easiest way to work with JSON in GWT. Here’s a modified code example from the linked article:

public class Customer extends JavaScriptObject {
    public final native String getFirstName() /*-{ 
        return this.first_name;
    }-*/;
    public final native void setFirstName(String value) /*-{
        this.first_name = value;
    }-*/;
    public final native String getLastName() /*-{
        return this.last_name;
    }-*/;
    public final native void setLastName(String value) /*-{
        this.last_name = value;
    }-*/;
}

Once you have the overlay type defined, it’s easy to create a JavaScript object from JSON and access its properties in Java:

public static final native Customer buildCustomer(String json) /*-{
    return eval('(' + json + ')');
}-*/;

If you want the JSON representation of the object again, you can wrap the overlay type in a JSONObject:

Customer customer = buildCustomer("{'Bart', 'Simpson'}");
customer.setFirstName("Lisa");
// Displays {"first_name":"Lisa","last_name":"Simpson"}
Window.alert(new JSONObject(customer).toString());

Leave a Comment