gpt4 book ai didi

java - GSON 和 InstanceCreator 问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:06 28 4
gpt4 key购买 nike

我有以下 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);

抛出:

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;
}
}

我能做什么?

更新

根据@raffian 的建议(他/她发布的链接),我实现了一个InterfaceAdapter完全就像链接中的那个(我没有改变任何)。现在我得到以下异常:

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)

有什么想法吗?

最佳答案

你看过this了吗? ?看起来是实现 InstanceCreator 的一种非常简洁的方法。

我也在使用 Gson,但切换到了 FlexJSON由于序列化问题。使用 Flex,您不需要实例创建者,只需确保您的对象具有基于 JavaBean 规范的所有字段的 getter/setter,就可以了:

 ShapeHolder sh = new ShapeHolder();
sh.addShape(new Rectangle());
sh.addShape(new Circle());
JSONSerializer ser = new JSONSerializer();
String json = ser.deepSerialize(sh);
JSONDeserializer<ShapeHolder> der = new JSONDeserializer<ShapeHolder>();
ShapeHolder sh2 = der.deserialize(json);

关于java - GSON 和 InstanceCreator 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447897/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com