You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 23:03:11