改造中如何处理两种不同的响应

时间:2018-07-09 04:13:49

标签: android json retrofit2 jsonschema2pojo

我跟随this使用Retrofit2发布数据

我使用JSON POJO来解析我的POST和GET文件

因此,如果记录中有数据,我将得到这种响应

{
"status": "200",
"response": [{
        "cnt_id": "201",
        "phn_no": "3251151515",
        "dat_cnt": "Reset Password request Said to Mail"
    },
    {
        "cnt_id": "209",
        "phn_no": "555465484684",
        "dat_cnt": "Hi DEMO User , Congratulations! Your account has been created successfully."
    },
    {
        "cnt_id": "210",
        "phn_no": "4774748",
        "dat_cnt": "Hi XYZ , Congratulations! Your account has been created successfully."
    }
]
}

如果没有数据,我会得到

{"status":"204","response":{"msg":"No Content"}}
{"status":"400","response":{"msg":"BadRequest"}}
{"status":"401","response":{"msg":"Unauthorized User"}}

所以在这里我可以解析状态200中的数据,但是当状态不等于200时我要处理它们

我尝试过

   status = response.body().getStatus();
   if(status.equals("200")) {
      List<Response> resList =  response.body(). getResponse();

            for(int i = 0; i<resList.size(); i++)
            {.
             .
              ..
             .
            }
        }

        else {
             //not Implemented
             }

现在我应该写些什么了,我在POJO中使用了不等于200的响应数据,但我要了它的清单

更新

com.example.Example.java

public class Example {
    @SerializedName("status") @Expose private String status;
    @SerializedName("response") @Expose private List<Response> response = null;
}        

com.example.Response.java

public class Response {
    @SerializedName("cnt_id") @Expose private String cntId;
    @SerializedName("phn_no") @Expose private String phnNo;
    @SerializedName("dat_cnt") @Expose private String datCnt;
}

5 个答案:

答案 0 :(得分:4)

您可以通过Retrofit2来获取errorBody()

制作一个名称为RestErrorResponse.java的POJO模型类以处理此响应。

  

{“状态”:“ 401”,“响应”:{“ msg”:“未经授权的用户”}}

并遵循以下信息:

 if (response.isSuccessful()) {

        // Your Success response. 

 } else {

        // Your failure response. This will handles 400, 401, 500 etc. failure response code


         Gson gson = new Gson();
         RestErrorResponse errorResponse = gson.fromJson(response.errorBody().charStream(), RestErrorResponse.class);
                    if (errorResponse.getStatus() == 400) {
                        //DO Error Code specific handling

                        Global.showOkAlertWithMessage(YourClassName.this,
                                getString(R.string.app_name),
                                strError);

                    } else {
                        //DO GENERAL Error Code Specific handling
                    }
                }

我通过这种方法处理了所有故障响应。希望这也可以对您有所帮助。

答案 1 :(得分:3)

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;
}

您的callBack方法应该类似于

new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> response) {
                if(response.isSuccessful()){
                    Example example = response.body();
                    Gson gson = new GsonBuilder().create();
                    if(example.status.equals("200")) {
                        TypeToken<List<Response>> responseTypeToken = new TypeToken<List<Response>>() {};
                        List<Response> 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<Example> call, Throwable t) {
                //Failure message
            }
        }

答案 2 :(得分:1)

class Response<T> {
        private String status;
        private T response;

        private boolean isSuccess() {
            return status.equals("200");
        }
    }

    class ListData {
        private String cnt_id;
        private String phn_no;
        private String dat_cnt;
    }

    class Error {
        private String msg;
    }

    public class MainResponse {
        @SerializedName("Error")
        private Error error;
        @SerializedName("AuthenticateUserResponse")
        private List<ListData> listData;
    }

@POST("listData")
Call<Response<MainResponse>> listData();

答案 3 :(得分:1)

您可以使用不同的pojo类来处理错误消息

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<ResponseBody, ResponseError> 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();
    }
}

成功的pojo类

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

错误pojo类

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

答案 4 :(得分:0)

因此,在您的情况下,有可能将响应标记类型设为 String/List<Response>。因此您将响应标记类型声明为 Object

@SerializedName("response") @Expose public Object response;

并在下面的代码片段改造的onResponse方法中编写代码

if (response.body().response!=null &&  response.body().response instanceof Collection<?>) {
            //if you find response type is collection then convert to json then json to real collection object
            String responseStr = new Gson().toJson(data.diagnosis.provisionalDiagnosis);
            Type type=new TypeToken<List<Response>>(){}.getType();
            List<Response> responseList=new Gson().fromJson(responseStr,type);
            if(responseList.size() > 0){
                binding.phoneTv.setText(responseList.get(0).phnNo);
            }
        }

我发现这是处理具有多种类型的单个标签的简单方法