Get difference types of JSON response Retrofit

风流意气都作罢 提交于 2019-12-08 12:57:42

问题


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?


回答1:


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



回答2:


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) {

        }
    });


来源:https://stackoverflow.com/questions/50794523/get-difference-types-of-json-response-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!