How to Handle Two Different Response in Retrofit

前端 未结 4 569
青春惊慌失措
青春惊慌失措 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 08:58

    you can use different pojo class to handle error msg

    status = response.body().getStatus();
    if(status.equals("200")) {
        ResponseSuccess res =  response.body();
        for(int i = 0; i < res.response.size(); i++){
            Log.d("TAG", "Phone no. " + res.response.get(i).phn_no);
        }
    } else {
        Converter converter = getRetrofitInstance().responseBodyConverter(ResponseError.class, new Annotation[0]);
        ResponseError error;
        try {
            error = converter.convert(response.errorBody());
            Log.e("TAG", error.response.msg);
        } catch (IOException e) {
            error = new ResponseError();
        }
    }
    

    success pojo class

    public class ResponseSuccess {
        public String status;
        public List response;
        public class Response{
            public String cnt_id;
            public String phn_no;
            public String dat_cnt;
        }
    }
    

    error pojo class

    public class ResponseError {
        public String status;
        public Response response;
        public class Response{
            public String msg;
        }
    }
    

提交回复
热议问题