Michael
Michael

Reputation: 33297

How do I serialize a complex Class in GWT?

I want to serialize the following class with AutoBeans.

public class GetResults<T extends Dto> implements Result {

    List<T> results;

    protected GetResults() {
    }

    public GetResults(List<T> results) {
        this.results = results;
    }

    public List<T> getResults() {
        return results;
    }

    public void setResults(List<T> results) {
        this.results = results;
    }
}

Here is what I tried but failed:

public class AutoBeanSerializer {
    private final AutoBeanFactory factory;
    public AutoBeanSerializer(AutoBeanFactory factory) {
        this.factory = factory;
    }

    public String <T> encodeData(T data) {
        AutoBean<T> autoBean = AutoBeanUtils.getAutoBean(data);
        return AutoBeanCodex.encode(autoBean);
    }

    public <T> T decodeData(Class<T> dataType, String json) {
        AutoBean<T> bean = AutoBeanCodex.decode(factory, dataType, json);
        return bean.as();
    }
}

The above code does not work the line with

public String encodeData(T data) {

Has these errors:

- T cannot be resolved to a type
- The type String is not generic; it cannot be parameterized with arguments 
 <T>

How do I serialize the above class with abstract types in GWT?

Upvotes: 1

Views: 615

Answers (2)

user2980344
user2980344

Reputation:

You can use this lib: https://code.google.com/p/gwt-streamer/

It will do the job if you implement Streamable in all your classes.

Here is an example from the documentation:

public class Person implements Streamable {
    // fields, visibility doesn't matter
    private String name;
    private int age;

    private Person() {}        // default no-args constructor is required

    public Person( String name, int age ) {
        this.name = name; this.age = age;
    }

    // getters, setters are optional...
}

Server and client use the same API for serialization.

Person person = new Person( "Anton", 33 );
String buffer = Streamer.get().toString( person );
//...
person = (Person) Streamer.get().fromString( buffer );
//...
Person personCopy = Streamer.get().deepCopy( person );

Upvotes: 1

Colin Alworth
Colin Alworth

Reputation: 18331

For the second part (unrelated to the first or the question in the title), there is a typo in the code that I made in the original answer. The method encodeData should have the generic arg T defined before the return type:

public <T> String encodeData(T data) {
    AutoBean<T> autoBean = AutoBeanUtils.getAutoBean(data);
    return AutoBeanCodex.encode(autoBean);
}

Note however that this code will not help for your first class, because AutoBeans are meant to be automatic implementations for bean-like interfaces, not for regular java classes. See http://code.google.com/p/google-web-toolkit/wiki/AutoBean for more details on how to use autobeans.

Upvotes: 2

Related Questions