使用Retrofit2解析favqs接口出现Gson MalformedJsonException错误如何解决
问题根因
- 接口请求路径错误:favqs公开的当日名言接口路径为
/qotd,你写的qotd_date是返回字段名不是接口路径,请求错误路径会返回404的HTML页面,不是合法JSON - 响应类型定义错误:该接口返回的是单个
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
相关产品推荐
相关产品推荐

