I need help.
I have an endpoint that takes a parameter. Depending on this parameter, the JSON
returned will be completely different.
Is it possible for RetroFit
to handle this?
For example:
http://myserver.com/all/<parameter>
where parameter is BUS
or BICYCLE
, as well as adding others later.
An example BUS
request will return:
"stops": [{
"Lat": "....",
"Lng": "....",
"Name": "Main Street",
"Route": "",
"StopNumber": "2"
}]
The BICYCLE
endpoint will return:
"stops": [{
"address": "Town Centre",
"lat": "....",
"lng": "....",
"number": "63",
"open": "1"
}]
Depending on which section of my Android app that the user is in, I would like to send a different parameter, and be able to handle it using the same call.
I was thinking of using a parent class called AllTypes
that each of the other classes extend, and then setting my Retrofit
call signature to:
@GET("/all/{type}")
void getAll(@Path("type") String type, Callback<AllTypes> callback);
But I'm not sure if Retrofit
can automatically pick the correct child class for AllTypes
based on the returned JSON
, or even the passed parameter type
.
Does anyone know how to do this? If not, I'll just have to create multiple different methods with different Callback types.
Thanks.
Just to close this off.
You can get the raw JSON back from RetroFit
and use GSON
to manually serialise to the class type you want.
For example:
RestClient.get().getDataFromServer(params, new Callback<JSONObject>() {
@Override
public void success(JSONObject json, Response response) {
if(isTypeA) {
//Use GSON to serialise to TypeA
} else {
//Use GSON to serialise to TypeB
}
}
});