android - 如何使用 Volley 从 JSON 对象中获取数组的值?
问题描述
我有这样的json结果
知道我在 andorid studio 中的代码是这样的在此处输入图像描述
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject object = response.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("list");
for (int i=0; i< jsonArray.length();i++){
JSONObject coba = jsonArray.getJSONObject(i);
String namapoli = coba.getString("namapoli");
mTextViewResult.append(namapoli);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
但为什么应用程序不显示结果?任何人都可以给我
解决方案
您正在尝试从 api 响应获取列表数组,而不是您定义的从 api 响应获取响应正文的对象:
改变 :
JSONArray jsonArray = response.getJSONArray("list");
至:
JSONArray jsonArray = object.getJSONArray("list");
最终视图将如下所示:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject object = response.getJSONObject("response");
JSONArray jsonArray = object.getJSONArray("list");
for (int i=0; i< jsonArray.length();i++){
JSONObject coba = jsonArray.getJSONObject(i);
String namapoli = coba.getString("namapoli");
mTextViewResult.append(namapoli);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
推荐阅读
- java - onResponse 内的空 ArrayList
- lua - 如何从redis中的多个哈希中获取HGET
- angular - Angular 5:加载外部 CSS 文件 - 不允许加载本地资源
- reactjs - 使用 uxMode='redirect'->react-google-login 时未触发 onSuccess?
- apache-spark - 加载类文件“XGBoost.class”时检测到 xgboost4j-spark 缺失或无效依赖项
- codeigniter - 添加www。来自 http:// 在 codeigniter 中尝试过的代码
- google-cloud-platform - GCE/GKE NAT 网关路由终止 ssh 连接
- android - Flutter:构建后应用程序未正确安装
- google-cloud-platform - 如何使用服务帐户模拟调用 gcloud
- db2 - 通过修改 db2(udb) 中表中数字列的不带双引号的方式从表中导出记录