解决Java中RecyclerView数据加载时Gson的BEGIN_OBJECT/BEGIN_ARRAY异常
问题解决:JsonSyntaxException 异常处理
问题原因
API返回的是JSON数组(以[开头),但你的代码期望解析成一个JSON对象(以{开头)——你用AllExpenseResponse类接收响应,而这个类定义了一个名为AllExpenseResponse的数组字段,和实际返回的结构完全不匹配,导致Gson解析失败。
解决方案
1. 修改ApiInterface的请求返回类型
把返回的Call<AllExpenseResponse>改成Call<List<AllExpenseResponseItem>>,直接匹配API返回的数组结构:
@GET("api/index.php?route=expenses") Call<List<AllExpenseResponseItem>> getAllExpenseItem(@Query("id") String userID);
2. 调整MainActivity中的请求回调逻辑
同步修改回调泛型类型,直接用响应体作为RecyclerView的数据源,无需再调用getAllExpenseResponse():
RestClient.getService().getAllExpenseItem(USER_ID).enqueue(new Callback<List<AllExpenseResponseItem>>() { @Override public void onResponse(Call<List<AllExpenseResponseItem>> call, Response<List<AllExpenseResponseItem>> response) { if (response.isSuccessful()) { expenseItem = response.body(); Log.i("responseExpense", expenseItem.toString()); adapter = new ExpenseAdapter(expenseItem, getApplicationContext()); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recyclerView.setAdapter(adapter); } } @Override public void onFailure(Call<List<AllExpenseResponseItem>> call, Throwable t) { Toast.makeText(MainActivity.this, "Something Wrong, Check Log for Details", Toast.LENGTH_SHORT).show(); Log.i("error", t.toString()); Log.i("error", call.toString()); } });
3. 可选优化:移除无用类
由于API并没有返回包含AllExpenseResponse字段的外层对象,AllExpenseResponse.java这个类已经没有作用,可以直接删除。
内容的提问来源于stack exchange,提问作者Hafiz Caniago
相关产品推荐
相关产品推荐

