Some time while we loading data from web service we need to read data from keys which are dynamic means that the keys are change according to data and you don”t have any fix keyword from which you extract data, so this post help you to do that. The best way to get your work done use Java Iterator.
What is Iterator ?
In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types ofiterators are often provided via a container’s interface. For more Iterator – Wikipedia, the free encyclopedia.
Get dynamic keys from JSON Data
Sample JSONData
If you want to learn to load data from server follow this post: Android JSON Parsing
{ "Cool": [ { "name": "UPS Freight", "star": "1" } ], "variable": [ { "class": "loading", "star": "1" } ] }
Code to extract data dynamically from JSON Data
public void getData(String data){ // Load json data and display JSONObject jsonData = new JSONObject(data); // Use loop to get keys from your response Iterator itr = jsonData.keys(); while(itr.hasNext()){ String keys = (String)itr.next(); Log.e("Keys", "----"+keys); JSONArray dynamicValue = jsonData.getJSONArray(keys); // Your stuff here } }
Hope this will help 🙂