Reputation: 141
i'm using Retrofit and RxJava to integrate with an API every api response is like that:
{"success":true,"message":null,"object":{"bla":"String", "bla1":1}}
And the only thing that change is the object
, i tried to create a "ResponseBase" and every model extends that, and create a "Response", that is what api will aways return
public class Response {
public Boolean success;
public String message;
public ResponseBase object;
}
And to get the object type i want i just cast in a .map
//VehicleResponseModel extends ResponseBase
VehicleResponseModel vec = (VehicleResponseModel) response.getObject();
But this error happens:
ResponseBase cannot be cast to VehicleResponseModel
i don't have in mind a clearly way to do that.
Upvotes: 2
Views: 504
Reputation: 482
If you're planning to go with generics you should read this : Serializing and Deserializing Generic Types
Or you can go with the answer Bartek mentioned above.
public class ResponseBase {
public Boolean success;
public String message;
}
public class VehicleResponseModel extends ResponseBase {
//Your custom vehicle model
}
And then make your retrofit interface return VehicleResponseModel.
Upvotes: 0
Reputation: 2769
Use generics for that:
public class Response<T> {
public Boolean success;
public String message;
public T object;
}
And make your retrofit return Response<VehicleResponseModel>
so you can retrieve your VehicleResponseModel
from it
Upvotes: 2
Reputation: 31458
I think the problem is in your inheritance model:
This should be your parent class:
public class Response {
public Boolean success;
public String message;
}
This could be one of the child classes (representing the included data model):
public class SomeResponse extends Response {
public InnerModel object;
public static class InnerModel {
public String bla;
public int bla1;
}
}
Then when you receive an instance of your SomeResponse
you can easily access e.g. someResponse.object.bla1
.
Upvotes: 1