简体   繁体   English

如何解析来自 retrofit 请求的以下错误响应?

[英]How to parse the following error response from retrofit request?

I am trying to parse an error body of a retrofit enqueue.我正在尝试解析 retrofit 队列的错误正文。 The log shows the response.errorBody as日志将 response.errorBody 显示为

"{"response":["Image height must not exceed image width. Try a different image."]}"

Here is my code:这是我的代码:

call.enqueue(new Callback<EditBlogResponse>() {
            @Override
            public void onResponse(Call<EditBlogResponse> call, Response<EditBlogResponse> response) {
                if(response.body() != null){
                    Log.d(TAG, "onEditResponse: " + response.body());
                    editBlogResponse.setValue(response.body().toString());
                }else{
                    try {
                        Log.d(TAG, "onResponseError: " + response.errorBody().string());
                        JSONObject jsonObject = new JSONObject(response.errorBody().string());
                        JSONArray jsonArray = jsonObject.getJSONArray("response");
                        editBlogResponse.setValue(jsonArray.getString(0));
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(Call<EditBlogResponse> call, Throwable t) {
                t.printStackTrace();
                editBlogResponse.setValue("failure");
            }
        });

I receive a system error我收到系统错误

W/System.err: org.json.JSONException: End of input at character 0 of 
    at org.json.JSONTokener.syntaxError(JSONTokener.java:460)
    at org.json.JSONTokener.nextValue(JSONTokener.java:101)
    at org.json.JSONObject.<init>(JSONObject.java:164)
    at org.json.JSONObject.<init>(JSONObject.java:181)
    at com.example.brandonblog.Repository.Repository$3.onResponse(Repository.java:176)
    at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Any ideas on what I am doing wrong?关于我做错了什么的任何想法?

Well, in that case, your expected response is also inside the onResponse() block.好吧,在这种情况下,您的预期响应也在onResponse()块内。 you have to lookup into block for the 400 or 4xx status code like this:您必须像这样查找4004xx状态代码的块:

  if(response.code() != 200) { 
        Log.d(TAG, "onEditResponseCode: " + response.code());
        Log.d(TAG, "onEditResponse: " + response.body());
        editBlogResponse.setValue(response.body().toString());
  } else {
        Log.d(TAG, "onEditResponsecode: " + response.code());
      Log.d(TAG, "onEditResponse: " + response.body().response.get(0));
      //because your message is always at the 0th position of the 'response' list
      // You don't need to use any JSONObject or JSONArray etc for these.
  }

Try and let me know if it works.尝试让我知道它是否有效。

Got it working, the problem was this line:得到它的工作,问题是这一行:

editBlogResponse.setValue(jsonArray.getString(0));

Instead of getString, it should be get():而不是 getString,它应该是 get():

editBlogResponse.setValue(array.get(0).toString());

Full working response:完整的工作响应:

public void onResponse(Call<EditBlogResponse> call, Response<EditBlogResponse> response) {
    if(response.body() != null){
        Log.d(TAG, "onEditResponse: " + response.body());
        editBlogResponse.setValue(response.body().toString());
    }else{
        try {
             JSONObject jObjError = new JSONObject (response.errorBody().string());
             JSONArray array = jObjError.getJSONArray("response");
             editBlogResponse.setValue(array.get(0).toString());
        } catch (JSONException e) {
             e.printStackTrace();
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}

Please try with below described POJO for parsing JSON.请尝试使用下面描述的 POJO 来解析 JSON。

public class EditBlogResponse {

@SerializedName("response")
@Expose
private List<String> response = null;

public List<String> getResponse() {
return response;
}

public void setResponse(List<String> response) {
this.response = response;
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM