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了解不多。这可能会有帮助。类似于使用默认序列化程序序列化响应对象并执行更多额外工作。