Java 多态反序列化

Java 多态反序列化,java,gson,Java,Gson,我有一个Vehicle接口,可以Car和Bus实现。服务器返回如下响应- { "id" : 10, "vehicle_type" : "Car", "vehicle" : { "id" : 100, "name" : "MyCar" } // More attributes. } 为其建模的对应类是 class Response { int id; String vehicle_type;

我有一个
Vehicle
接口,可以
Car
Bus
实现。服务器返回如下响应-

{
    "id" : 10,
    "vehicle_type" : "Car",
    "vehicle" : {
          "id"  : 100,
          "name" : "MyCar"
    }
    // More attributes.
}
为其建模的对应类是

class Response {
    int id;
    String vehicle_type;
    Vehicle vehicle;
    // More attributes.
}
响应
中的
车辆类型
声明了车辆的类型。我需要根据
车辆类型将
响应
反序列化为
响应
对象。如果是
Car
我需要使用
Car.class
反序列化
vehicle
,反序列化
response
Bus.class
,否则

如何使用gson实现这一点


EDIT-post的不同之处在于类类型(
type
)包含在需要反序列化的
jsonobject
中。这里不是。如果
vehicle\u type
vehicle
内,我可以为
vehicle
编写自定义反序列化程序,检查
vehicle\u type
并相应反序列化。但是我想我需要为
Response
编写一个自定义反序列化程序,在这里我创建一个新的
Response
对象,解析
vehicle\u type
,将其反序列化为
vehicle
对象,并通过解析手动将其和
Response
的其余属性添加到
Response
对象中。这是非常麻烦的,使用gson也没有真正的帮助。我希望有更好的解决办法。:)

因此我为
Response
编写了一个自定义反序列化程序,首先调用默认反序列化程序,获取
车辆类型
,并相应地执行
车辆
反序列化

public Response deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    Response response = new Gson().fromJson(jsonElement, Response.class);
    Type t = null;
    if (response.getVehicleType().equals(Bus.vehicle_type)) {
        t = Bus.class;
    } else if (response.getVehicleType().equals(Car.vehicle_type)) {
        t = Car.class;
    }
    JsonObject object = jsonElement.getAsJsonObject();
    if (object.has("vehicle")) {
        JsonElement vehicleElement = object.get("vehicle");
        Vehicle vehicle = jsonDeserializationContext.deserialize(vehicleElement, t);
        response.setVehicle(vehicle);
    }
    return response;
}

期待更好的解决方案。:)

你读过这篇文章吗@罗布,我刚去了。请检查编辑。@zack按照与前面文章相同的模型进行响应,并在其中使用
上下文。反序列化()
用于汽车/公共汽车-您不需要手动执行。请参阅对已接受答案的评论。@KDM我的意思是我必须手动将
response
的其他属性添加到对象中。@zack我对jackson了解不多。这可能会有帮助。类似于使用默认序列化程序序列化响应对象并执行更多额外工作。