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

求助:解决org.json.JSONArray无法转换为JSONObject异常

解决org.json.JSONArray cannot be converted to JSONObject异常

Hey,这个问题我之前也碰到过,属于非常典型的JSON数据类型不匹配问题!咱们先把问题根因理清楚:你用JsonObjectRequest去请求接口,但服务器返回的根数据结构是JSON数组([]),而不是你预期的JSON对象({}),所以当代码尝试把响应转换成JSONObject时,就直接抛出类型转换异常了。

具体解决方案分两步走:

1. 替换请求类型为JsonArrayRequest

把原来的JsonObjectRequest换成JsonArrayRequest,这样回调就能直接接收服务器返回的JSON数组,从根源上避免类型不匹配。

2. 调整响应处理逻辑

不需要再从JSONObject里去获取JSONArray,直接遍历接收到的JSONArray处理数据即可。

修改后的完整代码示例:

public void sendjsonrequest(){
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, 
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                try {
                    // 直接遍历返回的JSON数组
                    for(int i=0; i<response.length(); i++){
                        JSONObject dishObj = response.getJSONObject(i);
                        // 这里处理单个菜品对象,比如提取字段
                        String dishName = dishObj.getString("name");
                        double dishPrice = dishObj.getDouble("price");
                        // ... 你的其他业务逻辑
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
    
    // 记得把请求添加到Volley请求队列(假设你已经初始化了requestQueue)
    requestQueue.add(jsonArrayRequest);
}

额外排查小提示:

如果你确定服务器应该返回包含dish数组的JSON对象(比如格式是{"dish": [{}, {}]}),那你要检查:

  • 请求的url是否正确,有没有传错参数或者路径
  • 直接用浏览器/Postman访问这个url,确认服务器实际返回的内容是不是你预期的格式

内容的提问来源于stack exchange,提问作者Krishna Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:47:37