How to Handle Multiple Response in Rectrofit 2.2

March 13, 2018 , 0 Comments

How to Handle Multiple response in Rectrofit 2.2

When API Calling Response could not same at that time we can not handle in Api calling,

For Rectrofit Basic Learn this:

Than After Learn this : How to Gson Calling without Converting Object

Step 1: Interface integrate
public interface ApiService {
String BASEURL = "https://api.androidhive.info/";
@POST("contacts/")
Call getContactList();
}

Step 2: Setup
   private static void setupRestClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASEURL)
.client(client)
//no need to give any specific model to convert that
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService REST_CLIENT = retrofit.create(ApiService.class);

}

#RESPONSE :


{
"type":"model1","contact_list":".....(your data)"
}

Step 3:
 private void getContactList() {

Call getContact = RestClient.post().getContactList();
getContact.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
JsonElement jsonElement = response.body();
Log.e("Contact_List", jsonElement.toString());
//parse JSONELEMENT To JSONOBJECT
try {
JSONObject jb= new JSONObject(String.valueOf(response.body()));

//your Models
if(jb.getString("type").equals("model1")){
Model1 modelobj1=new Gson().fromJson(response.body(), Model1.class);
}else{
Model2 modelobj2=new Gson().fromJson(response.body(), Model2.class);
}

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


}

@Override
public void onFailure(Call call, Throwable t) {
Log.e("Contact_List", "failed");
}
});

}

Contributer

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

0 comments:

Popular Posts