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

Retrofit调用Get方法时出现Gson解析错误该如何解决

报错原因

该报错的核心是Gson解析时的JSON结构类型不匹配:

  • 你在Retrofit接口定义、回调参数中声明的返回类型为单个VW_AC_Line_对象,Gson预期解析{}包裹的JSON对象
  • 但Web API实际返回的是[{"ID":2665,"Section":"IT"}],属于[]包裹的JSON数组,因此触发类型校验失败

解决方法

方案1:安卓端适配现有接口返回(优先推荐,无需修改后端)

  1. 调整Retrofit接口定义,将回调泛型修改为数组类型List<VW_AC_Line_>:
@GET("/api/VW_AC_LINE_/deparment/{section}")
public void getSection(@Path("section") String section, Callback<List<VW_AC_Line_>> callback);
  1. 同步修改接口调用处的回调逻辑,取数组首个元素处理即可:
restService.getService().getSection(section, new Callback<List<VW_AC_Line_>>() {
    @Override
    public void success(List<VW_AC_Line_> studentList, Response response) {
        // 接口返回数组仅含1个元素,直接取第一位即可
        if (studentList != null && !studentList.isEmpty()) {
            VW_AC_Line_ student = studentList.get(0);
            Toast.makeText(Viewattendance.this, "success", Toast.LENGTH_LONG).show();
            // 原有业务逻辑保持不变
        }
    }

    @Override
    public void failure(RetrofitError error) {
        Toast.makeText(Viewattendance.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
    }
});

方案2:修改后端接口返回结构

如果该接口设计上本应返回单个对象,可修改后端返回逻辑,去掉外层数组包裹,直接返回如下结构即可,安卓端原有代码无需调整:

{"ID":2665,"Section":"IT"}

内容的提问来源于stack exchange,提问作者Nurul Nabila Mahadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:57:04