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

如何使用Volley读取API返回值并遍历sections判断active状态

问题诊断

你的代码存在两个核心问题:

  • 响应返回的sections是JSONObject类型,你误用getJSONArray()方法读取会直接抛出JSONException
  • 你已经直接拿到了Volley返回的JSONObject response,不需要再转成String重新构造JSONObject,属于冗余操作

可行实现代码

public void propertySelector() {
    String url = "myurl";

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                // 直接读取sections JSONObject,不要转JSONArray
                JSONObject sectionsObj = response.getJSONObject("sections");
                // 先读取全局enabled开关(如果需要判断的话)
                boolean isGlobalEnabled = sectionsObj.optBoolean("enabled", false);
                if (!isGlobalEnabled) {
                    // 全局未启用的业务逻辑可以写在这里
                    return;
                }
                // 拿到sections的所有key迭代器
                Iterator<String> keyIterator = sectionsObj.keys();
                while (keyIterator.hasNext()) {
                    String key = keyIterator.next();
                    // 跳过enabled字段,只处理业务模块节点
                    if ("enabled".equals(key)) {
                        continue;
                    }
                    // 读取当前模块的配置对象
                    JSONObject moduleObj = sectionsObj.optJSONObject(key);
                    if (moduleObj == null) {
                        continue;
                    }
                    // 判断active状态
                    boolean isActive = moduleObj.optBoolean("active", false);
                    if (isActive) {
                        // 这里写对应模块激活的业务逻辑
                        // 比如:根据key展示对应图片到Fragment
                        switch (key) {
                            case "Home":
                                // 展示Home对应的图片
                                break;
                            case "Activites":
                                // 展示Activites对应的图片
                                break;
                            // 其他模块同理
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("TAG", "Error: " + error.toString());
        }
    });
    volleyRequest.add(request);
}

注意事项

  • 这里用optBoolean、optJSONObject代替get系列方法,可以避免字段不存在时直接崩溃,适合接口字段不稳定的场景
  • 如果后续有新增模块,只需要在switch分支里加对应的处理逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 07:12:01