Retrofit+GSON场景下JSON数组数据提取失败问题求助
解决Retrofit+GSON场景下JSON子数组数据提取失败的问题
先直接说问题根源:你日志已经打印出子数组长度是1,但内层循环完全没执行,是因为内层循环的条件写错了!
你写的内层循环代码是:
for (int y = 0; i < mJsonArrayItems.length(); y++)
这里循环判断用了外层的变量i而非当前循环的y,当外层i=1时,i < 1不成立,循环直接跳过,自然不会执行里面的解析逻辑。
修正后的核心代码片段
把内层循环的条件改成y < mJsonArrayItems.length()即可:
for (int y = 0; y < mJsonArrayItems.length(); y++) { Log.d("Responders", "inside"); JSONObject jsonObject = mJsonArrayItems.getJSONObject(y); String username = jsonObject.getString("username"); String location = jsonObject.getString("coords"); responders.add(new ResponderObject("", username, "", "", location)); }
额外优化建议(结合你提到的Retrofit+GSON)
既然你已经在使用Retrofit和GSON,完全可以摆脱手动解析JSON的繁琐,直接定义对应的数据类让GSON自动解析,避免这类低级错误:
- 先定义匹配JSON结构的数据类:
// 对应外层数组第一个元素的结构 class InfoBean { @SerializedName("info") String info; } // 对应子数组里的对象结构 class ResponderBean { @SerializedName("username") String username; @SerializedName("coords") String coords; }
- 修改Retrofit接口方法,直接返回可解析的类型:
Call<List<Object>> responderList(int param);
- 在回调中通过GSON自动解析:
call.enqueue(new Callback<List<Object>>() { @Override public void onResponse(Call<List<Object>> call, Response<List<Object>> response) { if (response.isSuccessful()) { List<Object> result = response.body(); if (result != null && result.size() >= 2) { // 处理第一个元素:InfoBean InfoBean infoBean = new Gson().fromJson(new Gson().toJson(result.get(0)), InfoBean.class); new Flags(getApplicationContext()).checkFlag(infoBean.info); // 处理第二个元素:ResponderBean数组 List<ResponderBean> responderList = new Gson().fromJson( new Gson().toJson(result.get(1)), new TypeToken<List<ResponderBean>>(){}.getType() ); for (ResponderBean bean : responderList) { responders.add(new ResponderObject("", bean.username, "", "", bean.coords)); } } // 后续UI更新逻辑... } } @Override public void onFailure(Call<List<Object>> call, Throwable t) { handler.removeCallbacks(runnable); } });
这种方式不仅能避免手动解析的各种坑,代码也更简洁易维护。
内容的提问来源于stack exchange,提问作者jeanluc rotolo
相关产品推荐
相关产品推荐

