【问题标题】:Adapting Retrofit 2.0 responses using GSON for successful and failed response使用 GSON 调整 Retrofit 2.0 响应以获得成功和失败的响应
【发布时间】:2016-02-25 02:59:41
【问题描述】:

如何调整 Retrofit 2.0 以根据服务器响应调用正确的模型。

即成功返回 Json

{
  "status": "successful",
  "session_id": "123",
}

即失败的 Json 返回

{
  "status": "fail",
  "message": "Wrong Email",
}

我使用http://www.jsonschema2pojo.org 创建了登录模型。

然后我打电话给

@FormUrlEncoded
@POST(Constant.API_LOGIN)
Call<UserLogIn> userLogin(@FieldMap Map<String, String> params);

但如果登录失败,我需要使用这个:?

@FormUrlEncoded
@POST(Constant.API_LOGIN)
Call<UserLogInFalied> userLogin(@FieldMap Map<String, String> params);

我只需要 GSON 将响应映射到正确的模型? 任何建议如何克服这个/ 谢谢。

【问题讨论】:

    标签: android json gson retrofit androidhttpclient


    【解决方案1】:

    对此的一种解决方案是编写一个自定义反序列化器,因为您正在使用改造,我想您可以检查这个SO Question

    【讨论】:

    【解决方案2】:

    为什么不让你的 json 成功

    {
        status:"successful",
        message:" "
        seeesion_id:"123"
    }
    

    和错误的json

      {
            status:"failed",
            message:"wong email "
            seeesion_id:"-1"
        }
    

    【讨论】:

      【解决方案3】:

      创建一个父模型类,如下所示,并在 SuccessModel 和 ErrorModel 中扩展它。

      public class Model {
          boolean error;
      
          public boolean isError() {
              return error;
          }
      
          public void setError(boolean error) {
              this.error = error;
          }}
      

      在创建 Retrofit 实例之前添加以下代码:`

      OkHttpClient client = new OkHttpClient();
          client.interceptors().add(new Interceptor() {
              @Override
              public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                  Request request = chain.request();
                  com.squareup.okhttp.Response response     =chain.proceed(request);
      
                  MediaType content = MediaType.parse("Application/Json");
      
                  String res = response.body().string();
                  try {
                      JSONObject obj = new JSONObject(res);
                      if (obj.getString("status").equals("fail")) {
                          obj.put("error", true);
                          res = obj.toString();
                      }else{
                       return response;
                   }
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
      
                  ResponseBody b = ResponseBody.create(content, res);
                  return response.newBuilder().body(b).build();
              }
          });
      

      现在,如下编辑您的 onResponse() 方法:

        @Override
                  public void onResponse(Response<Model> response) {
                      Model model = response.body();
                      if (model.isError()) {
                           ErrorModel errorModel = (ErrorModel) model;
                          // your code accordingly
                      } else {
                          SuccessModel successModel = (SuccessModel)model;
                        // your code accordingly
                      }
      
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        • 1970-01-01
        • 2015-05-07
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 2017-08-06
        相关资源
        最近更新 更多