Search code examples
javaandroidretrofit

How to parse Error response with dynamic class in retrofit? (How to use JAVA Generic?)


I have a class utils and in it there is an parseError function. The goals is to describe the error response given from the retrofit. So I just need to call a function from a certain class.

public static BaseApiResponse<LoginResponse,LoginErrorResponse> parseError(Response<?> response) {
    try {
        Gson gson = new Gson();
        Type type = new TypeToken<BaseApiResponse<LoginResponse,LoginErrorResponse>>() {}.getType();
        return gson.fromJson(response.errorBody().charStream(), type);
    }catch(Exception e) {
        BaseApiResponse erResponse = new BaseApiResponse();
        erResponse.setMessage("Error unexpected in JSON!");
        return erResponse;
    }
}

Here is the full function I tried.

The problem is, I have a BaseResponseAPI<DATA, ERROR>, where the class has a dynamic object class parameter. How to make the function(parseError) that I created return dynamic object class data ? the example i want the call to be dynamic is like this:

BaseApiResponse<LoginResponse, LoginErrorResponse> errResponse = CommonUtils.parseError(response);

BaseApiResponse<RegisterResponse, RegisterErrorResponse> errResponse = CommonUtils.parseError(response);

Solution

  • You can edit function to use Java Generic like this:

    public static <D,E> BaseApiResponse<D,E> parseError(Response<?> response) {
        try {
            Gson gson = new Gson();
            Type type = new TypeToken<BaseApiResponse<LoginResponse,LoginErrorResponse>>() {}.getType();
            return gson.fromJson(response.errorBody().charStream(), type);
        }catch(Exception e) {
            BaseApiResponse<D,E> erResponse = new BaseApiResponse<D,E>();
            erResponse.setMessage("Error unexpected in JSON!");
            return erResponse;
        }
    }
    

    Then you can call the function like this:

    BaseApiResponse<LoginResponse, LoginErrorResponse> errResponse = CommonUtils.<LoginResponse, LoginErrorResponse>parseError(response);
    //or other generic class
    BaseApiResponse<RegisterResponse, RegisterErrorResponse> errResponse = CommonUtils.<RegisterResponse, RegisterErrorResponse>parseError(response);