Parse A Nested Json With Retrofit 2.0
i have this json's and i want to use retrofit for parsing them. { 'status': 'true', 'data': [ { 'id': '1', 'title': 'Hi :)', 'text': '
121212
', 'cat_Solution 1:
Root node of your json is not array, but you declared it as List<responseStatus>
at interface getPost
. So you need to use responseStatus
instead current one. And use gettter to access data
@SerializedName("data")private ArrayList<retroPost> data;
which is array
Solution 2:
I see many people face this issue so I post my own way with Retrofit here is what I've done it's so simple and clean :
create ServiceHelper Class :
publicclassServiceHelper {
privatestaticfinalStringENDPOINT="http://test.com";
privatestaticOkHttpClienthttpClient=newOkHttpClient();
privatestaticServiceHelperinstance=newServiceHelper();
private IPlusService service;
privateServiceHelper() {
Retrofitretrofit= createAdapter().build();
service = retrofit.create(IPlusService.class);
}
publicstatic ServiceHelper getInstance() {
return instance;
}
private Retrofit.Builder createAdapter() {
httpClient.setReadTimeout(60, TimeUnit.SECONDS);
httpClient.setConnectTimeout(60, TimeUnit.SECONDS);
HttpLoggingInterceptorinterceptor=newHttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
returnnewRetrofit.Builder()
.baseUrl(ENDPOINT)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create());
}
public Call<List<CategoryModel>> getAllCategory() {
return service.getAllCategory();
}
}
Then create your Service class in my Case it's IPlusService
publicinterfaceIPlusService {
@GET("/api/category")
Call<List<CategoryModel>> getAllCategory();
}
Now in your Fragment/Activity class you call your own method with something like this :
ServiceHelper.getInstance().getAllCategory().enqueue(newCallback<List<CategoryModel>>() {
@OverridepublicvoidonResponse(Response<List<CategoryModel>> response, Retrofit retrofit) {
processResponse(response);
}
@OverridepublicvoidonFailure(Throwable t) {
processResponse(null);
}
});
Also add following dependency to your gradle :
dependencies {
compile'com.squareup.retrofit:retrofit:2.0.0-beta2'compile'com.squareup.retrofit:converter-gson:2.0.0-beta2'compile'com.squareup.okhttp:logging-interceptor:2.6.0'
}
Post a Comment for "Parse A Nested Json With Retrofit 2.0"