Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Object in GWT

What's the simplest way to serialize a bean to a string using GWT? I prefer not to use GWT.create() invocations.

like image 213
Miguel Ping Avatar asked Apr 08 '09 15:04

Miguel Ping


1 Answers

Disclaimer: Serializing a bean on the URL isn't such a great idea for GWT. I've learned that if need to put data on the URL, it should be as little as possible and only what is necessary to restore the state of your page. Look at how Gmail uses its history tokens and you'll see it is pretty minimal.

With that disclaimer out of the way:

For a GWT project I worked on I simply wrote out values of the bean separated by a delimiter. When reading the values back in, I used the String.split() method to get an array. With that array I assign the values back to the right bean properties. In code:

public class Sample {

    private int a;
    private boolean b;
    private String c;
    //getters and setters for fields not shown

    public String toHistoryToken(){
        return a+"/"+b+"/"+c;
    }
    public void fromHistoryToken(String token){
        String[] values=token.split("/");
        a=Integer.parseInt(values[0]);
        b=Boolean.parseBoolean(values[1]);
        c=values[2];
    }
}

For more complicate scenarios you may have to do more complicated things. For example, for nested objects, you have to write the code to pass the values to the child object(s).

Also, be aware that you have to make sure that any values you use don't contain the delimiter. So if you know your Strings might contain "/" then you might have to do a replace() operation of them to escape any nested delimiters.

like image 99
Peter Dolberg Avatar answered Sep 30 '22 16:09

Peter Dolberg