Retrofit 2 RxJava - Gson - "全局"反序列化,更改响应类型

raf*_*kob 3 android json gson rx-java retrofit

我正在使用一个始终返回如下所示的JSON对象的API:

public class ApiResponse<T> {
    public boolean success;
    public T data;
}
Run Code Online (Sandbox Code Playgroud)

data field是一个JSON对象,包含所有有价值的信息.当然,对于不同的请求,它们是不同的.所以我的改造界面如下所示:

@GET(...)
Observable<ApiResponse<User>> getUser();
Run Code Online (Sandbox Code Playgroud)

当我想处理响应时我需要做的事如:

response.getData().getUserId();
Run Code Online (Sandbox Code Playgroud)

我真的不需要那个布尔成功字段,我想省略它,所以我的改装界面可能如下所示:

@GET(...)
Observable<User> getUser();
Run Code Online (Sandbox Code Playgroud)

在Gson可以这样做吗?或者可能是一个整洁的Rx功能,它会自动转换它?

编辑:示例json:

{
  "success": true,
  "data": {
    "id": 22,
    "firstname": "Jon",
    "lastname": "Snow"
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑2:我已经通过改装拦截器来手动修改响应体.它有效,但如果您有任何其他建议,请发布它们:)

raf*_*kob 6

正如Than所说,使用拦截器的解决方案并不是那么好.我已经设法用一个Rx变压器来解决这个问题.我还添加了自定义api异常,当出现问题时我可以抛出它并在onError中轻松处理它.我认为它更强大.

响应包装器:

public class ApiResponse<T> {
    private boolean success;
    private T data;
    private ApiError error;
}
Run Code Online (Sandbox Code Playgroud)

成功为false时返回错误对象:

public class ApiError {
    private int code;
}
Run Code Online (Sandbox Code Playgroud)

成功为假时抛出此异常:

public class ApiException extends RuntimeException {
    private final ApiError apiError;
    private final transient ApiResponse<?> response;

    public ApiException(ApiResponse<?> response) {
        this.apiError = response.getError();
        this.response = response;
    }

    public ApiError getApiError() {
        return apiError;
    }

    public ApiResponse<?> getResponse() {
        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

和一个变压器:

protected <T> Observable.Transformer<ApiResponse<T>, T> applySchedulersAndExtractData() {
    return observable -> observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .map(tApiResponse -> {
                if (!tApiResponse.isSuccess())
                    throw new ApiException(tApiResponse);
                else
                    return tApiResponse.getData();
            });
}
Run Code Online (Sandbox Code Playgroud)