Here is my Retrofit
instance:
@Provides
@Singleton
ApiManager provideApiManager() {
RxJava2CallAdapterFactory rxAdapter = RxJava2CallAdapterFactory.create();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
Gson gson = new GsonBuilder().create();
GsonConverterFactory converterFactory = GsonConverterFactory.create(gson);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConstants.BASE_URL)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(rxAdapter)
.client(okHttpClient)
.build();
return retrofit.create(ApiManager.class);
}
Model:
class AbstractMessage {
String id;
}
class TextMessage extends AbstractMessage {
String textMessage;
}
class ImageMessage extends AbstractMessage {
String url;
String text;
}
Request:
@GET("direct/messages")
Observable<List<AbstractMessage>> getMessages(@Header("Authorization") String authHeader, @Body RequestObject request);
Executing request:
apiManager.getMessages(authHeader, requestObject)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<AbstractMessage>>() {
@Override
public void accept(List<AbstractMessage> messages) throws Exception {
...
}
});
When I execute a request I receive a collection of AbstractMessage
objects. The JSON
can contain both text and image messages. In my case JSON
converter creates AbstractMessage
and maps only the id
field. How can I make converter to create TextMessage
and ImageMessage
objects map all matching fields and then cast it to AbstractMessage
. Or there may be some other solution.