简体   繁体   English

使用Retrofit2从API调用获得错误响应

[英]Error response from API call using Retrofit2

I want to make a call to the API and the error response comes in two ways. 我想调用API,错误响应有两种方式。

First is like this (where the message is an object with multiple string lists) 首先是这样的(其中消息是具有多个字符串列表的对象)

{
  "success": false,
  "message": {
    "email": [
        "Must be between 2 and 20 characters."
    ],
    "password": [
        "Must be between 2 and 25 characters."
    ]
  }
}

And the other is like this (where message is just a string) 另一个是这样的(消息只是一个字符串)

{
  "success": false,
  "message": "User with that email exists."
}

My model so far looks like this: 到目前为止我的模型看起来像这样:

public class ErrorResponse {

    @Expose
    @SerializedName("success")
    private boolean success;


    @Expose
    @SerializedName("message")
    private Message message;

    //constructor & getters & setters

    public class Message {

        @Expose
        @SerializedName("email")
        private List<String> email;

        @Expose
        @SerializedName("password")
        private List<String> password;

        //constructor & getters & setters
    }
}

How can I treat both cases of "message" in model class? 如何处理模型类中的“消息”两种情况?

简单的方法是在客户端中使用ErrorMessage属性并通过成功标志句柄呈现。

If this two pattern are fix then you can try below way : 如果这两个模式都已修复,那么您可以尝试以下方式:

ErrorResponse.java ErrorResponse.java

public class ErrorResponse {

@Expose
@SerializedName("success")
private boolean success;


@Expose
@SerializedName("message")
private MyMessage message;

public class MyMessage{

 private Message message;

 private String StrMessage;

}

//constructor & getters & setters

public class Message {

    @Expose
    @SerializedName("email")
    private List<String> email;

    @Expose
    @SerializedName("password")
    private List<String> password;

    //constructor & getters & setters
}
}

And when you want to use their value just check which kind of value it is like below. 当你想要使用它们的价值时,只需检查下面的价值类型。

if(StrMessage!=null){
//Message is string.
}
else{
//do your stuff. 
}

You should parse your JSON manually, For example if your JSON has message and your message has email tag then using the second model and if not using the first model, it works only if you have this two kind of messages. 你应该手动解析你的JSON,例如,如果你的JSON有message而你的message有电子邮件标签然后使用第二个模型,如果不使用第一个模型,它只有你有这两种消息时才有效。

something like this using Gson: 使用Gson这样的事情:

JsonElement rootTree = parser.parse(jsonRequest);
        if (rootTree.isJsonObject()) {

         JsonObject object = rootTree.getAsJsonObject();
         JsonElement message= object.get("message");

         if(message.isJsonObject()) {
                JsonElement email = message.get("email");

                if(email != null) {
                          //Use second model
                } else {
                          //Use first model                     
                }
         }
}

You can try something like this, 你可以尝试这样的事情,

       JSONObject json = new JSONObject(response);
        if (json.has("message")) {
            if (json.get("message") instanceof String) {
                message = json.getString("message");
            } else if (json.get("message") instanceof JSONObject) {
                JSONObject jsonObject = json.getJSONObject("message");
                if (jsonObject.has("email")) {
                    JSONArray array = jsonObject.getJSONArray("email");
                    for (int i = 0; i < array.length(); i++) {
                        email.add(array.getString(i));
                    }
                }
                if (jsonObject.has("password")) {
                    JSONArray array = jsonObject.getJSONArray("password");
                    for (int i = 0; i < array.length(); i++) {
                        password.add(array.getString(i));
                    }
                }
            }
        }

Don't forget to handle JSONException. 不要忘记处理JSONException。

Try this, It is working for me. 试试这个,它对我有用。 and it's a easiest way to handle this kind of response. 这是处理这种响应的最简单方法。

API request using ResponseBody, 使用ResponseBody的API请求,

Call<ResponseBody> call = .......

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                try {
                    if (response.body() != null && response.body().string() != null) {

                        Object json = new JSONTokener(response.toString()).nextValue();

                        if (json instanceof JSONArray) {
                            MyResponse1 myResponse = new Gson().fromJson(response.body().string(), MyResponse1.class);
                            myResponse.getMessage().getEmail();
                        } else if (json instanceof JSONObject) {

                            MyResponse2 myResponse = new Gson().fromJson(response.body().string(), MyResponse2.class);
                            myResponse.getMessage();
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // Handle exception here
            }
        });

Take two object class for two different response: 为两个不同的响应取两个对象类:

// MyResponse1.java // MyResponse1.java

public class MyResponse1 {


    private boolean success;
    private MessageBean message;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public MessageBean getMessage() {
        return message;
    }

    public void setMessage(MessageBean message) {
        this.message = message;
    }

    public static class MessageBean {
        private List<String> email;
        private List<String> password;

        public List<String> getEmail() {
            return email;
        }

        public void setEmail(List<String> email) {
            this.email = email;
        }

        public List<String> getPassword() {
            return password;
        }

        public void setPassword(List<String> password) {
            this.password = password;
        }
    }
}

// MyResponse2.java // MyResponse2.java

public class MyResponse2 {


    private boolean success;
    private String message;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

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

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