I have a Vehicle
interface which Car
and Bus
implement. The server returns a response like this -
{
"id" : 10,
"vehicle_type" : "Car",
"vehicle" : {
"id" : 100,
"name" : "MyCar"
}
// More attributes.
}
The corresponding class to model it is
class Response {
int id;
String vehicle_type;
Vehicle vehicle;
// More attributes.
}
The vehicle_type
in the response
declares what kind of vehicle it is. I need to deserialize the response
into a Response
object depending on the vehicle_type
. If it is Car
I need to use Car.class
for deserializing vehicle
during the deserialization of response
and Bus.class
if it is otherwise.
How can I achieve this using gson?
EDIT - This post is different in the sense that class type(type
) is contained within the jsonobject
that needs to deserialized. Here it is not. If vehicle_type
was inside vehicle
, I could write a custom deserializer for Vehicle
, check the vehicle_type
and deserialize accordingly. But I think I would need to write a custom deserializer for Response
where I create a new Response
object, parse vehicle_type
, deserialize it into a Vehicle
object accordingly and add it and rest of attributes of response
to the Response
object manually by parsing them. This is very cumbersome and using gson doesn't really help then. I was hoping for a better solution. :)