0

I am trying to make a small example using Volley and Gson. I have the below-posted code. The INTERNET permission was added. Now the URL I have contains JSON data. This JSON data contains several properties and some of the are array of objects. For example,

{
    "header":{
       "headerTitle":"Check2 Shape Compararison",
       "headerDescription":"List of geometric products"
    },
    "filters":[
       "Alle",
       "Verfügbar",
       "Vorgemerkt"
    ],
    "products":[
       {

       },
       {

       }
    ]
}

Initially, I don't know anything about the structure of the JSON file. What I want to do is, to iterate through the contents of the JSON file to get the name of each property. For example, I want to get the following:

header
filters
products

how this can be achieved using Volley??

error:

 private void fetchJSONObjectRequest() {
    Log.w(TAG, "<fetchJSONObjectRequest>");
    this.mJSONObjectRequest = new JsonObjectRequest(Request.Method.GET, this.BASE_URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i(TAG, "<onResponse> response: " + response);

            try {
                Log.i(TAG, "<onResponse> response: " + response.getJSONArray("products"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    this.mRequestQueue.add(this.mJSONObjectRequest);
}
Community
  • 1
  • 1
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • header is a `json` object, filters is `json Array` and products is also a `json Array` – Abdul Kawee Aug 16 '18 at 05:56
  • @AbdulKawee i know, but is there any way using Volley to iterate through the response object to get the names of properties: header. filters and products? – Amrmsmb Aug 16 '18 at 05:59
  • @Letsamrlt check the answer below – Abdul Kawee Aug 16 '18 at 06:43
  • Possible duplicate of [To get all the keys in JSONObject into String array](https://stackoverflow.com/questions/20419217/to-get-all-the-keys-in-jsonobject-into-string-array) – Manohar Aug 16 '18 at 06:43

1 Answers1

0

if you want to get the keys of all the objects in volley response you can do it like this

Iterator iterator   = jsonObject.keys();
List<String> keysList = new ArrayList<String>();
while(iterator.hasNext()) {
    String key = (String) iterator.next();
    keysList.add(key);
}

and then you can fetch them same code

response.getJSONArray(keysList[0]); // or iterating over loop

Hope this helps

Abdul Kawee
  • 2,687
  • 1
  • 14
  • 26