[英]Deserializing to a templated class with Gson
I have a class with a nested subclass 我有一个带有嵌套子类的类
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;}
}
}
Currently I would like to be able to have a function that takes as a parameter the held class, and returns an appropriate instance of GenericClassHolder, ie something like my current code: 目前,我希望能够拥有一个函数,该函数将所保存的类作为参数,并返回适当的GenericClassHolder实例,即类似于我当前的代码:
GenericClassHolder<ExampleClassA> genericA = parseJson(jsonString, ExampleClassA.class);
with 与
<T> GenericClassHolder<T> parseJson(final String jsonString, Class<T> variableClass) throws JsonSyntaxException {
return GSON.fromJson(jsonString, new TypeToken<GenericClassHolder<T>>(){}.getType());
}
But this does not work in my current implementation, with the error 但这在我当前的实现中不起作用,出现错误
Unable to invoke no-args constructor for
GenericClassHolder<T>
.无法为
GenericClassHolder<T>
调用no-args构造函数。 Register an InstanceCreator with Gson for this type may fix this problem.使用此类型向Gson注册InstanceCreator可能会解决此问题。
How can I succinctly achieve my aforementioned goal of having a function that takes as input the specification for a class that may change and parses to this object accordingly? 我如何简洁地实现我的上述目标,即拥有一个功能,该功能将可能更改的类的规范作为输入并相应地解析到该对象? If it is not possible to achieve an elegant solution through a function, how can I achieve this goal without one?
如果无法通过一种功能来实现优雅的解决方案,那么如果没有一个功能,我怎么能实现这一目标呢?
I deployed this code in a Google Appengine instance, and due to some security reasons, I could not deserialize the way I was deserializing and replicate the same way on my local machine. 我在Google Appengine实例中部署了此代码,由于安全原因,我无法反序列化反序列化的方式,并且无法在本地计算机上以相同的方式进行复制。 The solution was to make the deserialized classes static;
解决的办法是使反序列化的类成为静态的。 they were nested inside of an outer encapsulating class as well
它们也嵌套在外部封装类中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.