本文介绍了在RetroFit中处理来自同一终结点的不同JSON响应类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助.

我有一个带参数的端点.根据此参数,返回的JSON将完全不同.

I have an endpoint that takes a parameter. Depending on this parameter, the JSON returned will be completely different.

RetroFit是否可以处理此问题?

Is it possible for RetroFit to handle this?

例如:

http://myserver.com/all/<parameter>

其中参数为BUSBICYCLE,以及以后添加其他参数.

where parameter is BUS or BICYCLE, as well as adding others later.

示例BUS请求将返回:

"stops": [{
    "Lat": "....",
    "Lng": "....",
    "Name": "Main Street",
    "Route": "",
    "StopNumber": "2"
}]

BICYCLE端点将返回:

"stops": [{
    "address": "Town Centre",
    "lat": "....",
    "lng": "....",
    "number": "63",
    "open": "1"
}]

根据用户所在的Android应用程序的哪个部分,我想发送一个不同的参数,并能够使用相同的调用来处理它.

Depending on which section of my Android app that the user is in, I would like to send a different parameter, and be able to handle it using the same call.

我当时在考虑使用一个名为AllTypes的父类,其他每个类都可以扩展该父类,然后将我的Retrofit调用签名设置为:

I was thinking of using a parent class called AllTypes that each of the other classes extend, and then setting my Retrofit call signature to:

@GET("/all/{type}")
void getAll(@Path("type") String type, Callback<AllTypes> callback);

但是我不确定Retrofit是否可以根据返回的JSON甚至传递的参数typeAllTypes自动选择正确的子类.

But I'm not sure if Retrofit can automatically pick the correct child class for AllTypes based on the returned JSON, or even the passed parameter type.

有人知道该怎么做吗?如果没有,我只需要创建具有不同回调类型的多个不同方法即可.

Does anyone know how to do this?If not, I'll just have to create multiple different methods with different Callback types.

谢谢.

推荐答案

只需将其关闭即可.

您可以从RetroFit获取原始JSON,并使用GSON手动序列化为所需的类类型.

You can get the raw JSON back from RetroFit and use GSON to manually serialise to the class type you want.

例如:

RestClient.get().getDataFromServer(params, new Callback<JSONObject>() {
    @Override
    public void success(JSONObject json, Response response) {
        if(isTypeA) {
            //Use GSON to serialise to TypeA        
        } else {
            //Use GSON to serialise to TypeB
        }
    }
});

这篇关于在RetroFit中处理来自同一终结点的不同JSON响应类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:14