java – 多态性如何与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字段.如何使转换器创建TextMessage和ImageMes​​sage对象映射所有匹配的字段,然后将其强制转换为AbstractMessage.或者可能还有其他一些解决方案.

解决方法:

您必须为对象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();

RuntimeTypeAdapterFactory.java不随Gson包一起提供,因此您必须手动下载.

您可以阅读有关运行时适配器herehere的更多信息

请注意,你的问题的标题应该是“与Gson的多态性”

我希望它有所帮助.

上一篇:java – 使用泛型类型和通用字段名称的GSON反序列化


下一篇:java – 使用GSON将JSON解析为POJO