Get difference types of JSON response Retrofit

2019-06-14 12:24发布

I have REST api which respond according to current state at the same path. Let's assume /api/users response with

{
  "status":200,
  "error":false,
  "users":["a","b"]
} 

if user is authorised. Else if user is not authorised it respond with {"status":403,"error":true,"redirect":"url"}. When defining Interface for api calls with Retrofit it needs the exact type of response object.

Ex:

@GET("users")
Call<List<User>> getUsers()

But here API server respond with different shapes of object. How to handle this type of situation?

2条回答
Lonely孤独者°
2楼-- · 2019-06-14 12:56

Opinion based answer

A Base class

public class BaseResponse{
    int status;
    String error;
    ...
    ...
}

A success response class

public class SuccessResponse extends BaseResponse{
    String[] users;
    ...
    ...
}

A failure response class

public class FailureResponse extends BaseResponse{
    String redirect;
    ...
    ...
}

API interface

@GET("users")
Call<BaseResponse> getUsers()

When data arrives

if(response.code == 200)
    // Parse with SuccessResponse Class
else
    // Parse with FailureResponse class
查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-14 13:02

use this class as your model pojo

public class User {

@SerializedName("status")
@Expose
private int status;
@SerializedName("error")
@Expose
private String error;
@SerializedName("users")
@Expose
private String users;

public int getStatus() {
    return status;
}

public void setStatus(int status) {
    this.status = status;
}

public String getError() {
    return error;
}

public void setError(String error) {
    this.error = error;
}

public String getUsers() {
    return users;
}

public void setUsers(String users) {
    this.users = users;
}

}

and call this model in your retrofit as...

Call<List<User>> res = BaseUrlClass.yourInterfaceHere().getUsers();
    res.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(Call<List<User>> call, Response<List<User>> response) {
            int stat;
            String err,uuser;
            List<User> a = response.body();
           for(int i = 0;i<a.size;i++){
                  User u = a.get(i);
                   stat = u.getStatus();
                   err = u.getError();
                   uuser = u.getUsers();

            if(stat == 200){
                   //do this
              } else{
                    //do this
                  }
        }

        @Override
        public void onFailure(Call<List<User>> call, Throwable t) {

        }
    });
查看更多
登录 后发表回答