Android中如何通过Volley获取JSONArray并解析数据
解决Volley解析含datas数组的JSON时的JSONException问题
嗨,刚接触Volley处理JSON确实容易踩这种坑!你遇到的org.json.JSONException大概率是因为把包含数组的JSON对象当成了直接的JSON数组来请求解析——毕竟返回的JSON结构是包含res字段和datas数组的对象,不是单纯的数组,直接用JsonArrayRequest肯定会报错。
先确认下你提到的返回JSON结构大概是这样的(如果和你的实际返回有出入,调整字段名即可):
{
"res": "success",
"datas": [
{"id": 1, "title": "测试数据1"},
{"id": 2, "title": "测试数据2"}
]
}
下面是正确的实现步骤和代码:
1. 用JsonObjectRequest替代JsonArrayRequest
核心错误就是请求类型选错了,因为接口返回的是JSON对象,不是JSON数组,所以要用JsonObjectRequest来发起请求。
2. 正确的解析代码
// 替换成你的接口URL String requestUrl = "你的接口地址"; // 创建JsonObjectRequest实例 JsonObjectRequest jsonRequest = new JsonObjectRequest( Request.Method.GET, requestUrl, null, // 请求体,GET请求传null即可 new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // 先读取res字段,判断请求状态(可选,但建议做) String responseStatus = response.getString("res"); if ("success".equals(responseStatus)) { // 获取datas数组 JSONArray datasArray = response.getJSONArray("datas"); // 遍历数组,拼接所有数据到字符串 StringBuilder resultContent = new StringBuilder(); for (int i = 0; i < datasArray.length(); i++) { // 取出数组里的每个对象 JSONObject dataItem = datasArray.getJSONObject(i); // 根据你的实际字段读取值,这里假设id和title是示例字段 int itemId = dataItem.getInt("id"); String itemTitle = dataItem.getString("title"); resultContent.append("第").append(i+1).append("条数据:\n") .append("ID: ").append(itemId).append("\n") .append("标题: ").append(itemTitle).append("\n\n"); } // 把解析结果设置到txtResponse txtResponse.setText(resultContent.toString()); } else { txtResponse.setText("接口返回失败:" + responseStatus); } } catch (JSONException e) { e.printStackTrace(); txtResponse.setText("JSON解析出错:" + e.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); // 友好提示错误信息 txtResponse.setText("请求失败:" + (error.getMessage() != null ? error.getMessage() : "未知错误")); } } ); // 将请求添加到Volley请求队列 Volley.newRequestQueue(getApplicationContext()).add(jsonRequest);
3. 额外注意事项
- 权限检查:确保你的
AndroidManifest.xml里添加了网络权限:<uses-permission android:name="android.permission.INTERNET" /> - 字段名大小写敏感:代码里
getString("res")、getJSONArray("datas")的字段名必须和返回JSON里的完全一致,大小写不能错! - 处理空值情况:如果
datas可能为空数组或者不存在,可以用optJSONArray("datas")替代getJSONArray,避免抛出异常;也可以先判断response.has("datas")再读取。 - 主线程安全:Volley的回调方法本身就在主线程,所以直接调用
txtResponse.setText()是安全的,不用额外切换线程。
内容的提问来源于stack exchange,提问作者Syahmi Shafawi
相关产品推荐
相关产品推荐

