繁体   English   中英

使用Gson反序列化为模板化类

[英]Deserializing to a templated class with Gson

我有一个带有嵌套子类的类

public class OuterClass {
class GenericClassHolder<R> {
    @SerializedName("results")
    List<R> results;

    public GenericClassHolder() {}

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

class ExampleClassA {
    @SerializedName("A")
    int a;

    public ExampleClassA() {}

    public int getA() {return a;}
}


class ExampleClassB {
    @SerializedName("B")
    String b;

    public ExampleClassA() {}

    public String getB() {return b;}
}
}

目前,我希望能够拥有一个函数,该函数将所保存的类作为参数,并返回适当的GenericClassHolder实例,即类似于我当前的代码:

GenericClassHolder<ExampleClassA> genericA = parseJson(jsonString, ExampleClassA.class);

<T> GenericClassHolder<T> parseJson(final String jsonString, Class<T> variableClass) throws JsonSyntaxException {
    return GSON.fromJson(jsonString, new TypeToken<GenericClassHolder<T>>(){}.getType());
}

但这在我当前的实现中不起作用,出现错误

无法为GenericClassHolder<T>调用no-args构造函数。 使用此类型向Gson注册InstanceCreator可能会解决此问题。

我如何简洁地实现我的上述目标,即拥有一个功能,该功能将可能更改的类的规范作为输入并相应地解析到该对象? 如果无法通过一种功能来实现优雅的解决方案,那么如果没有一个功能,我怎么能实现这一目标呢?

我在Google Appengine实例中部署了此代码,由于安全原因,我无法反序列化反序列化的方式,并且无法在本地计算机上以相同的方式进行复制。 解决的办法是使反序列化的类成为静态的。 它们也嵌套在外部封装类中

暂无
暂无

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

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