Java GSON 和 InstanceCreator 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20447897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GSON and InstanceCreator issue
提问by IAmYourFaja
I have the following POJOs:
我有以下 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
}
I have no problem getting GSON to serialize an instance of ShapeHolder
to JSON. But when I try to deserialize a String of that JSON back into a ShapeHolder
instance, I get errors:
让 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.construct(ConstructorConstructor.java:167)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:162)
... rest of stack trace ommitted for brevity
So I looked hereand started implementing my own ShapeInstanceCreator
:
所以我看这里并开始实现我自己的ShapeInstanceCreator
:
public class ShapeInstanceCreator implements InstanceCreator<Shape> {
@Override
public Shape createInstance(Type type) {
// TODO: ???
return null;
}
}
But now I'm stuck: I'm only given a java.lang.reflect.Type
, but I really need a java.lang.Object
so I can write code like:
但现在我被困住了:我只得到了一个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;
}
}
What can I do?
我能做什么?
Update
更新
Per @raffian's suggestion (the link he/she posted), I implemented an InterfaceAdapter
exactlylike the one in the link (I didn't change anything). Now I'm getting the following exception:
根据@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)
Any ideas?
有任何想法吗?
采纳答案by raffian
Did you look at this? Looks like a nice clean way to implement InstanceCreators.
你看这个了吗?看起来是实现 InstanceCreators 的一种非常干净的方式。
I was using Gson too, but switched to FlexJSONdue to serialization issues. With Flex, you don't need instance creators, just make sure your objects have getters/setters for all fields based on JavaBean spec, and you're good to go:
我也使用 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);
回答by Kanagavelu Sugumar
NOTE that FlexJSONis adding class name as part of json like below serialize time.
请注意,FlexJSON将类名添加为 json 的一部分,如下所示序列化时间。
{
"HTTPStatus": "OK",
"class": "com.XXX.YYY.HTTPViewResponse",
"code": null,
"outputContext": {
"class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
"eligible": true
}
}
So JSON will be cumber some; but you don't need write InstanceCreator
which is required in GSON.
所以JSON会有些麻烦;但您不需要编写InstanceCreator
GSON 中所需的内容。