我在Android Studio中使用Retrofit 1.9.0从我的REST API获取响应。
我想要做的方法是GET,在此网址上:http://dotfreeride.com/api/rest/adventures.php
我成功检索了另一个API的响应,但只有一个对象,这有3个大对象。
我的IApiMethods界面是这样的:
@GET("/adventures.php")
JSONObject getAdventures(
Callback<AdventuresApi> cb
);
My AdventuresApi(Model class)是这样的:
public class AdventuresApi {
public String adventure_id;
public String trimaps_context;
public String name;
public String video_url;
public List<ArrayPoi> array_poi;
public class ArrayPoi {
String poi_id;
String name;
String lat;
String lng;
String video_url;
}
}
活动中的My Retrofit调用是这样的:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
IApiMethods methods = restAdapter.create(IApiMethods.class);
Callback callback = new Callback() {
@Override
public void success(Object o, Response response) {
}
@Override
public void failure(RetrofitError error) {
Log.e("JSON", "NO DATA!");
}
};
methods.getAdventures(callback);
我真的不知道如何获取对象,我想得到对象的名称(例如:trimaps_context是&#34;动词&#34;,我需要名字&#34;粉末猎犬&#34)
对于单个对象,我在onResponse(Object o, Response response)
:
(ProfileApi) profileData = (ProfileApi) o;
Log.e("JSON", profileData.name + " " + profileData.email);
答案 0 :(得分:3)
1)您正在尝试将同步和异步调用结合起来。如果要异步执行请求,则必须按如下方式定义:
@GET("/adventures.php")
void getAdventures(
Callback<List<AdventuresApi>> cb
);
2)每次调用请求时都不要创建RestAdapter
实例。这真的是重量级的操作。使用singleton pattern。然后,您只需致电:
ApiManager.getAdapter().getAdventures(...);
3)对象映射由参数化Callback
类提供:
ApiManager.getAdapter().getAdventures(
new Callback<List<AdventuresApi>>() {
@Override
public void success(List<AdventuresApi> adventures, Response response) {
// here you can access the adventures list
}
@Override
public void failure(RetrofitError error) {
// handle error
}
});