具有可变维数组的Java对象
我正在尝试使用解析一个JSON,我有一个JSON,看起来像这样(简化):具有可变维数组的Java对象,java,arrays,json,generics,gson,Java,Arrays,Json,Generics,Gson,我正在尝试使用解析一个JSON,我有一个JSON,看起来像这样(简化): 当我尝试使用double[][][]而不是?时,我得到了一个com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为double,但在第6行第146列的BEGIN\u数组中 当我尝试将Shape作为一个抽象类,并为MultiPolygon和Polygon使用子类时,Gson尝试实例化Shape和错误 我可以使用泛型或其他狡猾的方法来解决
- 当我尝试使用
而不是double[][][]
时,我得到了一个?
com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为double,但在第6行第146列的BEGIN\u数组中
- 当我尝试将
作为一个抽象类,并为Shape
和MultiPolygon
使用子类时,Polygon
尝试实例化Gson
和错误Shape
我可以使用泛型或其他狡猾的方法来解决这个问题吗?您需要有自己的自定义,因为
坐标变量没有一组定义的数组维度。我建议对形状使用接口,然后为其编写反序列化程序,如下所示:
public interface Shape {
ShapeType getType();
enum ShapeType { Polygon, MultiPolygon }
}
然后是每种类型的实现<代码>形状类型.多边形
:
public class PolygonShape implements Shape {
private final ShapeType type = ShapeType.Polygon;
private double[][][] coordinates;
public ShapeType getType() {
return type;
}
public double[][][] getCoordinates() {
return coordinates;
}
public void setCoordinates(double[][][] coordinates) {
this.coordinates = coordinates;
}
}
public class MultiPolygonShape implements Shape {
private final ShapeType type = ShapeType.MultiPolygon;
private double[][][][] coordinates;
public ShapeType getType() {
return type;
}
public double[][][][] getCoordinates() {
return coordinates;
}
public void setCoordinates(double[][][][] coordinates) {
this.coordinates = coordinates;
}
}
和ShapeType.MultiPolygon
:
public class PolygonShape implements Shape {
private final ShapeType type = ShapeType.Polygon;
private double[][][] coordinates;
public ShapeType getType() {
return type;
}
public double[][][] getCoordinates() {
return coordinates;
}
public void setCoordinates(double[][][] coordinates) {
this.coordinates = coordinates;
}
}
public class MultiPolygonShape implements Shape {
private final ShapeType type = ShapeType.MultiPolygon;
private double[][][][] coordinates;
public ShapeType getType() {
return type;
}
public double[][][][] getCoordinates() {
return coordinates;
}
public void setCoordinates(double[][][][] coordinates) {
this.coordinates = coordinates;
}
}
最后,反序列化程序将依赖于每个实现的类型
:
public class ShapeDeserializer implements JsonDeserializer<Shape> {
@Override
public Shape deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
ShapeType type = context.deserialize(jsonObject.get("type"), ShapeType.class);
switch (type) {
case Polygon:
return context.deserialize(json, PolygonShape.class);
case MultiPolygon:
return context.deserialize(json, MultiPolygonShape.class);
default:
throw new JsonParseException("Unrecognized shape type: " + type);
}
}
}
不要忘记使用以下方法注册:
case Line:
return context.deserialize(json, LineShape.class);
GsonBuilder builder;
// ...
builder.registerTypeAdapter(Shape.class, new ShapeDeserializer());