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

使用Retrofit2解析favqs接口出现Gson MalformedJsonException错误如何解决

问题根因

  1. 接口请求路径错误:favqs公开的当日名言接口路径为/qotd,你写的qotd_date是返回字段名不是接口路径,请求错误路径会返回404的HTML页面,不是合法JSON
  2. 响应类型定义错误:该接口返回的是单个Example实体对象,你定义成了List<Example>列表类型,Gson无法将单个对象解析为列表,触发格式异常

修改步骤

1. 修正请求接口Client

public interface Client {
    // 修正请求路径为qotd,返回值改为单个Example对象
    @GET("qotd")
    Call<Example> reposForUser();
}

2. 修正MainActivity中的请求逻辑

public class MainActivity extends AppCompatActivity {

    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.pagination_list);

        // 可选:如果仍有解析兼容问题,可配置开启Gson宽松解析
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl("https://favqs.com/api/")
                // 传入自定义gson实例(不需要的话也可以保持原来的create())
                .addConverterFactory(GsonConverterFactory.create(gson));

        Retrofit retrofit = builder.build();

        Client client = retrofit.create(Client.class);
        Call<Example> call = client.reposForUser();

        call.enqueue(new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> response) {
                if(!response.isSuccessful() || response.body() == null){
                    Toast.makeText(MainActivity.this, "请求失败,错误码:"+response.code(), Toast.LENGTH_SHORT).show();
                    return;
                }
                Example result = response.body();
                // 单个对象转列表适配你的现有适配器
                List<Example> repos = new ArrayList<>();
                repos.add(result);
                listView.setAdapter(new MyAdapter(MainActivity.this, repos));
            }

            @Override
            public void onFailure(Call<Example> call, Throwable t) {
                Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
                t.printStackTrace();
            }
        });
    }
}

内容的提问来源于stack exchange,提问作者Semenov Nilolay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:48:04