【发布时间】:2015-02-06 09:14:48
【问题描述】:
如果我使用 接口 或 抽象类 注册 JsonSerializer,例如:
GsonBuilder builder = new GsonBuilder()
.registerTypeAdapter(MyInterface.class, new MySerializer());
Gson gson = builder.create();
MyInterface i = new MyConcreteClass();
String json = gson.toJson(i); // <--- Serializer is not invoked
序列化程序根本没有在gson.toJson() 中调用。
但是,如果我有一个包含 MyInterface 的类:
public class MyAnotherClass {
MyInterface i;
// ...
}
MyAnotherClass c = new MyAnotherClass()
String json = gson.toJson(c); // <--- Serializer is invoked
序列化器被调用。
对我来说,这是一种不一致的行为。它作用于成员变量的方式是寻找 declared 类型而不是 actual 类型,但它作用于“根”对象的方式是不同的。
这是错误/缺陷还是预期行为?如果这是意料之中的,背后有什么原因吗?
【问题讨论】:
标签: java gson serialization