How to consume this JSON structure via Retrofit 2?

前端 未结 2 815
予麋鹿
予麋鹿 2020-12-12 06:28

Hello I have a json structure and I need to get the datas from url. How can I do that? What are classes and functions. Please help me. Thanks.

here is my json.

2条回答
  •  萌比男神i
    2020-12-12 06:55

    Use jsonschema2pojo.org Paste you responce and it will generate Java classes for you. You instantiate Retrofit instance by setting all necessary components like this:

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
    

    and your interfaces will look like:

    @GET("api/service/schedule/{filial}")
        Observable>> getSchedule(@Path("filial") String filial);
    

    where @GET- annotation defining request type, Response<> - type used by Retrofit, carrying information whether response is successful or not (see class methods). Observable<> - type from rxJava library, allowing to process request in reactive way. I strongly recommend to use RxJava, because it simplifies execution in background very much. (DON't use AsyncTasks!!).

    in order to use Retrofit2 add following lines to your Gradle file:

       //Reactive programming
        compile 'io.reactivex:rxjava:1.1.5'
        compile 'io.reactivex:rxandroid:1.2.0'
    
    
        compile 'com.google.code.gson:gson:2.4'
        //retrofit and okhttp
        compile 'com.squareup.okhttp3:okhttp:3.2.0'
        compile 'com.squareup.retrofit2:retrofit:2.0.2'
        compile 'com.squareup.retrofit2:converter-gson:2.0.2'
        compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    

    You will instantiate Retrofit2 interface by a similar call: retrofit.create(Api.class)

提交回复
热议问题