Retrofit2,如何将响应转换为基类?

时间:2016-05-25 22:49:02

标签: android retrofit2

我的回复有基类。当出现问题(如身份验证问题)时,会调用此类。

public class DefaultResponse
{
    private transient Integer status;
    private String            property;
    private String            message;
    private String            developerMessage;
    protected String          code;

    public void setResponse(final Response response)
    {
        if (this.status != null)
        {
            return;
        }

        if (response != null)
        {
            try
            {
                final Object obj = response.body();
                if (obj != null && obj instanceof DefaultResponse)
                {
                    this.status = response.code();
                    this.message = ((DefaultResponse) obj).message;
                    this.developerMessage = ((DefaultResponse) obj).developerMessage;
                    this.property = ((DefaultResponse) obj).property;
                    this.code = ((DefaultResponse) obj).code;
                }
            }
            catch (final Exception ignored)
            {

            }
        }
    }

...
}

其余的回应正在扩展这个类。

public class FeatureResponse extends DefaultResponse 
{
    // Implementation
}

这是我用来调用API以获取功能的方法。

    public void getFeatures(final Location location)
    {
        Call<FeatureResponse> call = mService.getPassengerFeatures(location);
        call.enqueue(new Callback<FeatureResponse>()
        {
            @Override
            public void onResponse(Call<FeatureResponse> call, Response<FeatureResponse> response)
            {
                Logger.debug("Test", "Instance of response: " + response.getClass());

                FeatureResponse featureResponse = new FeatureResponse();

                if (response.isSuccessful())
                {
                    //...
                }

                featureResponse.setResponse(response);
                EventBus.post(featureResponse);
            }

            @Override
            public void onFailure(Call<FeatureResponse> call, Throwable t)
            {
                Logger.error(TAG, "getPassengerFeatures.onFailure(), msg: " + t.getMessage());

                FeatureResponse featureResponse = new FeatureResponse();
                featureResponse.setFailure(t);
                EventBus.post(featureResponse);
            }
        });
    }

当我发送请求时,这是我的服务器响应:

{"status":403,"code":4030,"property":"","message":"Unauthorized access","developerMessage":"Unauthorized access"}

因此,调用onResponse,创建FeatureResponse的新对象并调用featureResponse.setResponse(response);。正如您在上面的代码中看到的,我正在尝试获取其HTTP状态代码。但是,问题是if (obj != null && obj instanceof DefaultResponse)始终为false,因为response是类retrofit2.Response的实例。

是否可以将Response转换为DefaultResponse

1 个答案:

答案 0 :(得分:0)

当我使用Gson

以这种方式收到401,400 am等错误时
if (response.code() == 400) 
{
   Gson gson = new GsonBuilder().create();
   MyPojoError myPojoError=new MyPojoError ();
   try {
         myPojoError= gson.fromJson(response.errorBody().string(),MyPojoError .class);
        } catch (IOException e) {  // handle failure to read error   }

}

使用Pojo转换回Gson时,您还需要注释:

public class MyPojoError {

@SerializedName("error")
@Expose
private String error;
@SerializedName("error_description")
@Expose
private String errorDescription;

/**
 *
 * @return
 * The error
 */
public String getError() {
    return error;
}

/**
 *
 * @param error
 * The error
 */
public void setError(String error) {
    this.error = error;
}

/**
 *
 * @return
 * The errorDescription
 */
public String getErrorDescription() {
    return errorDescription;
}

/**
 *
 * @param errorDescription
 * The error_description
 */
public void setErrorDescription(String errorDescription) {
    this.errorDescription = errorDescription;
}

}

将示例Json回复粘贴到网站,选择来源类型 JSON ,注释: Gson Json Schema to Pojo

build.gradlecompile 'com.google.code.gson:gson:2.6.2'