[英]Serialize abstract class with Gson returns null
I have a problem with goggles Gson library.我的护目镜 Gson 库有问题。 Look at following code:
看下面的代码:
public abstract class Main {
public String foo = "foo";
public List<String> bar = Arrays.asList( "foo", "bar" );
@Override
public String toString( ) {
Gson gson = new Gson( );
return gson.toJson( this );
}
public static void main( String[] args ) {
Main main = new Main( ) {
};
System.out.println(main.toString( ));
}
}
It prints null
.它打印
null
。 But I would like it to print {"foo":"foo","bar":["foo","bar"]}
which it does, when I remove the abstract identifier and the curly brackets after the creation of Main( )
.但我希望它打印
{"foo":"foo","bar":["foo","bar"]}
当我在创建Main( )
。
So how do I get the right output for an abstract class?那么如何获得抽象类的正确输出呢?
In case of abstract classes, you will need write your own adapter.对于抽象类,您需要编写自己的适配器。 See this article on the subject.
请参阅有关该主题的这篇文章。
Looking at the code, I can see that Gson excludes anonymous inner classes.查看代码,我可以看到 Gson 排除了匿名内部类。 The best explanation I have is because Gson's philosophy is to support symmetric serialization and deserialization, as explained in this bug :
我有最好的解释是因为 Gson 的哲学是支持对称序列化和反序列化,正如这个 bug 中所解释的:
Don't use double brace initialization.
不要使用双括号初始化。 It prevents [de]serialization and Gson is designed for symmetric serialization and [de]serialization.
它可以防止 [反] 序列化,而 Gson 专为对称序列化和 [反] 序列化而设计。
It is impossible to deserialize an inner class without customization.没有定制就不可能反序列化内部类。 From the users guide :
从用户指南:
Gson can also deserialize static nested classes.
Gson 还可以反序列化静态嵌套类。 However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization.
但是,Gson 不能自动反序列化纯内部类,因为它们的无参数构造函数还需要对反序列化时不可用的包含对象的引用。
Thus Gson prevents the serialization.因此 Gson 阻止了序列化。 You could make the anonymous inner class a static nested class instead, and it would work.
您可以将匿名内部类改为静态嵌套类,它会起作用。
Sorry a bit late into this but for those who don't want to create nested class you can use this:抱歉有点晚了,但对于那些不想创建嵌套类的人,您可以使用它:
AbstractPayload payload = new AbstractPayload("field") {};
String result = gson.toJson(payload, AbstractPayload.class)
This worked for my case这适用于我的情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.