繁体   English   中英

如何在GWT中序列化复杂类?

[英]How do I serialize a complex Class in GWT?

我想用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;
    }
}

这是我尝试但失败的原因:

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();
    }
}

上面的代码与行无关

public String encodeData(T data){

有这些错误:

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

如何在GWT中使用抽象类型序列化上述类?

对于第二部分(与标题中的第一部分或问题无关),我在原始答案中的代码中存在拼写错误。 方法encodeData应该在返回类型之前定义泛型arg T:

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

但请注意,此代码对第一个类没有帮助,因为AutoBeans意味着是类bean接口的自动实现,而不是常规java类。 有关如何使用自动转移的详细信息,请参阅http://code.google.com/p/google-web-toolkit/wiki/AutoBean

您可以使用此库: https//code.google.com/p/gwt-streamer/

如果您在所有类中实现Streamable,它将完成这项工作。

以下是文档中的示例:

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...
}

服务器和客户端使用相同的API进行序列化。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM