【发布时间】:2019-12-24 21:07:42
【问题描述】:
我正在对这个 Google Books API URL做出回应
我有一个改造请求:'
public interface BookApiService {
@GET("/books/v1/volumes")
Call<Books> getBooks(@Query("q") String query);
}
并且有一个实体类
Books.java
public class Books {
@SerializedName("items")
@Expose
private List<Book> items;
public List<Book> getItems() {
return items;
}
}
和Book.java
public class Book {
@SerializedName("title")
@Expose
private String mTitle;
public String getTitle() {
return mTitle;
}
}
请求工作正常,我的意思是连接没有错误,并且改造返回 onResponse,而不是 onFailure。 但我的字符串“标题”为空。我怎么能得到这个。请通过上面的链接检查 JSON 响应。
更新:
改装电话:
public class BookService{
private static final String BASE_URL = "https://www.googleapis.com/";
private BookApiService mApiService;
private BookCallback mListener;
public BookService(BookCallback listener){
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
mApiService = retrofit.create(BookApiService.class);
mListener = listener;
}
public void getBooks(String query){
Call<Books> call = mApiService.getBooks(query);
call.enqueue(new Callback<Books>() {
@Override
public void onResponse(Call<Books> call, Response<Books> response) {
mListener.notifyDataReceived(response.body());
}
@Override
public void onFailure(Call<Books> call, Throwable t) {
mListener.notifyErrorReceived(t);
}
});
}
public interface BookCallback{
void notifyDataReceived(Books books);
void notifyErrorReceived(Throwable error);
}
BookCallback 监听器是我的 MainActivity: 当我检查日志时,有
"SUCCESS" "TITLE 1 null"
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
new BookService(this).getBooks("android");
}
@Override
public void notifyDataReceived(Books books) {
if(books.getItems() != null) {
List<Book> items = books.getItems();
Log.d(TAG, "Success");
Log.d(TAG, "TITLE 1" + items.get(0).getTitle());
setupAdapter(items);
}
}
【问题讨论】:
-
请在此处发布您的改造电话。
-
@Kabir 请检查,更新!
-
请编辑您的问题以包含minimal reproducible example。特别是,你怎么称呼
getBooks()?query的值是多少?另外,我建议使用 Postman 等工具手动发出请求以查看返回的内容。 -
试试这个:Log.d(TAG, "TITLE 1" + items.get(0).getVolumeInfo().getTitle());
-
@Code-Apprentice 正如您在 JSON 响应中看到的那样,有一个我转换为
Books.class的对象,在此对象内我有一个数组items,我将其转换为List<Book>,在这个数组里面,有另一个对象volumeInfo,我需要title