Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

android - How to consume this JSON structure via Retrofit 2?

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.

{
nodes: [
{
node: {
title: "...",
field_news_image: [
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."}
],
body: "...",
field_category: "...",
created: "..."
}
},
{
node: {
title: "...",
field_news_image: [
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."}
],
body: "...",
field_category: "...",
created: "..."
}
}
]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Response<List<Event>>> 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...