So I'm trying to get all the keys within a specific JSON Object but only the last key is obtained.
public void setUpSearch(JSONObject data_json){
Iterator<String> keys = data_json.keys();
while (keys.hasNext()) {
//get the key
String key = keys.next();
scripts = new ArrayList<String>();
scripts.add(key);
Log.i(TAG, key);
Log.i(TAG, String.valueOf(scripts));
}
Logtagging key shows all keys (around 300 of em), however logtagging scripts shows only the last one.
Any help will be highly appreciated.
Because there is a BUG in your code. ArrayList
initialization should be outside loop, otherwise you're overwriting previous one every time.
Use below code:
public void setUpSearch(JSONObject data_json){
Iterator<String> keys = data_json.keys();
scripts = new ArrayList<String>();
while (keys.hasNext()) {
//get the key
String key = keys.next();
scripts.add(key);
Log.i(TAG, key);
Log.i(TAG, String.valueOf(scripts));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.