Parse a nested json with retrofit 2.0

前端 未结 2 1361
再見小時候
再見小時候 2020-12-21 09:32

i have this json\'s and i want to use retrofit for parsing them.

{
  \"status\": \"true\",
  \"data\": [
{
  \"id\": \"1\",
  \"title\": \"Hi :)\",
  \"text         


        
2条回答
  •  感情败类
    2020-12-21 10:16

    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 :

    public class ServiceHelper {
    
    private static final String ENDPOINT = "http://test.com";
    
    private static OkHttpClient httpClient = new OkHttpClient();
    private static ServiceHelper instance = new ServiceHelper();
    private IPlusService service;
    
    
    private ServiceHelper() {
    
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IPlusService.class);
    }
    
    public static ServiceHelper getInstance() {
        return instance;
    }
    
    private Retrofit.Builder createAdapter() {
    
        httpClient.setReadTimeout(60, TimeUnit.SECONDS);
        httpClient.setConnectTimeout(60, TimeUnit.SECONDS);
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
    
        return new Retrofit.Builder()
                .baseUrl(ENDPOINT)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create());
    }
    
    public Call> getAllCategory() {
        return service.getAllCategory();
    }
    

    }

    Then create your Service class in my Case it's IPlusService

        public interface IPlusService {
    
        @GET("/api/category")
        Call> getAllCategory();
    }
    

    Now in your Fragment/Activity class you call your own method with something like this :

    ServiceHelper.getInstance().getAllCategory().enqueue(new Callback>() {
            @Override
            public void onResponse(Response> response, Retrofit retrofit) {
                processResponse(response);
            }
    
            @Override
            public void onFailure(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'
    
    }
    

提交回复
热议问题