这是我的Retrofit实例:
@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);
}
模型:
class AbstractMessage {
String id;
}
class TextMessage extends AbstractMessage {
String textMessage;
}
class ImageMessage extends AbstractMessage {
String url;
String text;
}
请求:
@GET("direct/messages")
Observable<List<AbstractMessage>> getMessages(@Header("Authorization") String authHeader, @Body RequestObject 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 {
...
}
});
当我执行一个请求时,我收到了一个AbstractMessage对象的集合. JSON可以包含文本和图像消息.在我的例子中,JSON转换器创建AbstractMessage并仅映射id字段.如何使转换器创建TextMessage和ImageMessage对象映射所有匹配的字段,然后将其强制转换为AbstractMessage.或者可能还有其他一些解决方案.
解决方法:
您必须为对象AbstractMessage,TextMessage和ImageMessage创建一个RuntimeTypeAdapterFactory,然后必须将其设置为gson实例.
假设你有这些对象:
public class Animal {
protected String name;
protected String type;
public Animal(String name, String type) {
this.name = name;
this.type = type;
}
}
public class Dog extends Animal {
private boolean playsCatch;
public Dog(String name, boolean playsCatch) {
super(name, "dog");
this.playsCatch = playsCatch;
}
}
public class Cat extends Animal {
private boolean chasesLaser;
public Cat(String name, boolean chasesLaser) {
super(name, "cat");
this.chasesLaser = chasesLaser;
}
}
下面是您需要的RuntimeTypeAdapter,以便正确地反序列化(和序列化)这些对象:
RuntimeTypeAdapterFactory<Animal> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
.of(Animal.class, "type")
.registerSubtype(Dog.class, "dog")
.registerSubtype(Cat.class, "cat");
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(runtimeTypeAdapterFactory)
.create();
类RuntimeTypeAdapterFactory.java不随Gson包一起提供,因此您必须手动下载.
请注意,你的问题的标题应该是“与Gson的多态性”
我希望它有所帮助.