How to Handle Two Different Response in Retrofit

前端 未结 4 591
青春惊慌失措
青春惊慌失措 2021-01-06 08:10

I followed this to POST Data Using Retrofit2

I Used JSON POJO to Parse my POST and GET files

So Here If Data inside the Records Is there I will get This Kind

4条回答
  •  不要未来只要你来
    2021-01-06 09:02

    public class Example {
        @SerializedName("status") @Expose private String status;
        @SerializedName("response") @Expose private Object response = null;
    }
    
    public class Response {
        @SerializedName("cnt_id") @Expose private String cntId;
        @SerializedName("phn_no") @Expose private String phnNo;
        @SerializedName("dat_cnt") @Expose private String datCnt;
    }
    
    public class ResponseError{
        @SerializedName("msg") @Expose private String msg;
    }
    

    And Your callBack methods should be like

    new Callback() {
                @Override
                public void onResponse(Call call, Response response) {
                    if(response.isSuccessful()){
                        Example example = response.body();
                        Gson gson = new GsonBuilder().create();
                        if(example.status.equals("200")) {
                            TypeToken> responseTypeToken = new TypeToken>() {};
                            List responseList = gson.fromJson(gson.toJson(example.getResponse()), responseTypeToken.getType());
                        } else {
                            //If for everyOther Status the response is Object of ResponseError which contains msg.
                            ResponseError responseError = gson.fromJson(gson.toJson(example.getResponse()), ResponseError.class);
                        }
                    }
                }
    
                @Override
                public void onFailure(Call call, Throwable t) {
                    //Failure message
                }
            }
    

提交回复
热议问题