1

How can I adapt the Retrofit 2.0 to call the right model according to the server response.

i.e Json return for Successfully

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

i.e Json return for Failed

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

I created login model using http://www.jsonschema2pojo.org.

then I call

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

but if the login failed I would need to use this : ?

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

I just need the GSON to map the response to the correct model ? Any advice how to over come this/ Thanks.

Thiago
  • 12,778
  • 14
  • 93
  • 110

3 Answers3

0

One solution for this is to write a custom deserializer, because you're using retrofit, I think you can check this SO Question

Community
  • 1
  • 1
reidzeibel
  • 1,622
  • 1
  • 19
  • 24
  • Hello I found a great article, but this is for the Retrofit 1.9. Do you how to implement for 2.0 - under Errors handling -> http://blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/ Thanks – Thiago Nov 23 '15 at 05:20
0

Why not make your successful json

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

and wrong json

  {
        status:"failed",
        message:"wong email "
        seeesion_id:"-1"
    }
jfxu
  • 690
  • 1
  • 5
  • 15
0

Create a parent Model class like following and extend it in both of your SuccessModel and ErrorModel.

public class Model {
    boolean error;

    public boolean isError() {
        return error;
    }

    public void setError(boolean error) {
        this.error = error;
    }}

Add the following code just before creating Retrofit instance:`

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

Now, Edit your onResponse() method as follows:

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

            }
Harish Sharma
  • 360
  • 1
  • 2
  • 7