我有以下 POJO:
public interface Shape {
public double calcArea();
public double calcPerimeter();
}
public class Rectangle implement Shape {
// Various properties of a rectangle
}
public class Circle implements Shape {
// Various properties of a circle
}
public class ShapeHolder {
private List<Shape> shapes;
// other stuff
}
我让 GSON 序列化一个实例没有问题ShapeHolder
到 JSON。但是当我尝试将该 JSON 的字符串反序列化回ShapeHolder
例如,我收到错误:
String shapeHolderAsStr = getString();
ShapeHolder holder = gson.fromJson(shapeHodlderAsStr, ShapeHolder.class);
Throws:
Exception in thread "main" java.lang.RuntimeException: Unable to invoke no-args constructor for interface
net.myapp.Shape. Register an InstanceCreator with Gson for this type may fix this problem.
at com.google.gson.internal.ConstructorConstructor$8.construct(ConstructorConstructor.java:167)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:162)
... rest of stack trace ommitted for brevity
所以我看了看here并开始实施我自己的ShapeInstanceCreator
:
public class ShapeInstanceCreator implements InstanceCreator<Shape> {
@Override
public Shape createInstance(Type type) {
// TODO: ???
return null;
}
}
但现在我陷入困境:我只得到了java.lang.reflect.Type
,但我真的需要一个java.lang.Object
所以我可以编写如下代码:
public class ShapeInstanceCreator implements InstanceCreator<Shape> {
@Override
public Shape createInstance(Type type) {
Object obj = convertTypeToObject(type);
if(obj instanceof Rectangle) {
Rectangle r = (Rectangle)obj;
return r;
} else {
Circle c = (Circle)obj;
return c;
}
return null;
}
}
我能做些什么?
Update
根据 @raffian 的建议(他/她发布的链接),我实现了InterfaceAdapter
exactly就像链接中的一样(我没有改变anything)。现在我遇到以下异常:
Exception in thread "main" com.google.gson.JsonParseException: no 'type' member found in what was expected to be an interface wrapper
at net.myapp.InterfaceAdapter.get(InterfaceAdapter.java:39)
at net.myapp.InterfaceAdapter.deserialize(InterfaceAdapter.java:23)
有任何想法吗?