多态性如何与Gson(Retrofit)协同工作

时间:2017-11-06 10:13:47

标签: java android json gson retrofit

这是我的 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字段。如何使转换器创建TextMessageImageMessage对象映射所有匹配的字段,然后将其强制转换为AbstractMessage。或者可能还有其他一些解决方案。

1 个答案:

答案 0 :(得分:26)

您必须为对象AbstractMessage,TextMessage和ImageMes​​sage创建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();

GSON包附带了类RuntimeTypeAdapterFactory.java,因此您必须手动下载。

您可以阅读有关运行时适配器herehere

的更多信息

请注意,问题的标题应为&#34;与Gson的多态性&#34;

我希望它有所帮助。