这是我的Retrofit实例:
@ProvIDes@Singletonapimanager provIDeapimanager() { RxJava2CallAdapterFactory rxAdapter = RxJava2CallAdapterFactory.create(); Ok@R_301_6822@ClIEnt ok@R_301_6822@ClIEnt = new Ok@R_301_6822@ClIEnt.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(ok@R_301_6822@ClIEnt) .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包一起提供,因此您必须手动下载.
您可以阅读有关运行时适配器here和here的更多信息
请注意,你的问题的标题应该是“与Gson的多态性”
我希望它有所帮助.
总结以上是内存溢出为你收集整理的java – 多态性如何与Gson一起工作(Retrofit)全部内容,希望文章能够帮你解决java – 多态性如何与Gson一起工作(Retrofit)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)