android - Retrofit2/GSON 无法转换为对象
问题描述
我正在使用 Retrofit2 向 Google Books API 提出请求并使用 GSON 转换器,但出现错误
ErrorExpected BEGIN_ARRAY 但在第 1 行第 2 列路径 $ BEGIN_OBJECT
这是我的
图书服务.java
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){
final ApiResponse apiResponse = new ApiResponse();
Call<List<Book>> call = mApiService.getBooks(query);
call.enqueue(new Callback<List<Book>>() {
@Override
public void onResponse(Call<List<Book>> call, Response<List<Book>> response) {
apiResponse.setBooks(response.body());
mListener.notifyDataReceived(apiResponse);
}
@Override
public void onFailure(Call<List<Book>> call, Throwable t) {
apiResponse.setError(t);
mListener.notifyDataReceived(apiResponse);
}
});
}
public interface BookCallback{
void notifyDataReceived(ApiResponse apiResponse);
}
}
和我的界面
BookApiService.java
public interface BookApiService {
@GET("/books/v1/volumes")
Call<List<Book>> getBooks(@Query("q") String query);
}
然后从实现 BookCallback的MainActivity.java发出请求
public class MainActivity extends AppCompatActivity implements BookService.BookCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
new BookService(this).getBooks("android");
}
}
解决方案
您的响应不是数组。它是一个包含数组的对象。
要解决此问题,您必须创建其他响应类,例如BookResponse
BookResponse.java
public class BookResponse{
@SerializedName("kind")
private Sting kind;
@SerializedName("totalItems")
private Int totalItems;
@SerializedName("items")
private List<Book> items;
}
像这样改变你的界面
public interface BookApiService {
@GET("/books/v1/volumes")
Call<BookResponse> getBooks(@Query("q") String query);
}
推荐阅读
- autodesk-forge - 您可以在 Autodesk Forge 示例程序中使用多种类型的传感器吗?
- flutter - 如何在 Flutter 中忽略 Snackbar 的指针事件
- r - 使用 For 循环创建多个表
- google-analytics - 如何从 UA 查询资源管理器中获取非抽样数据?
- pandas - 将原始数据集的子集与附加信息合并到父数据集
- java - 反射方法时的Java ClassCastException
- python - 如何将复杂的 Python 对象映射到 pandas 数据框?
- python - 如何在 Django 中使用 Python 中的多处理从 xml 文件创建数千个模型实例?
- python - 如何编写输出如下的 Python 程序: 限制:18 连续总和:1 + 2 + 3 + 4 + 5 + 6 = 21
- kubernetes - 无法附加或挂载卷:等待条件超时