如何使用截击从 API 中读取值?

How to read values from an API using volley?

我有一个简单的应用程序,可以根据响应调用 API,我想在片段上显示一些图像, 但我很难阅读回复。

下面是我使用的响应示例代码。

通过这样做,我能够读取响应,但不知道如何遍历并确定逻辑是否处于活动状态。

response.getJSONObject("sections");

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) {

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(String.valueOf(response));

                    JSONArray jsonArray = jsonObject.getJSONArray("sections");
                   
                } catch (JSONException e) {
                    e.printStackTrace();
                } 

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", "Error: " + error.toString());
            }
        });
        volleyRequest.add(request);
    }
}

sections: {
    Home: {
        active: true
    },
    Activites: {
        active: false
    },
    enabled: true, 
},

假设部分:{...} 是响应

您正在尝试将部分作为 JSONArray 读取,但它是一个对象,您必须这样读取它:

jsonObject = new JSONObject(String.valueOf(response));
Iterator<String> sectionKeys = jsonObject.keys();
while(sectionKeys.hasNext()){
   String sectionKey = iter.next();
   if (sectionKey.equals("enabled")) {
      Boolean enabled = jsonObject.getBoolean("enabled");
      ...
   } else {
      JSONObject sectionObject = jsonObject.getJSONObject(sectionKey);
      Boolean active = sectionObject.getBoolean("active")
      ...
   }
}