0

I am playing around for the first time with android development. I am trying to make a simple currency converter app. The particular piece I am working on is populating a spinner box with all of the available currencies without having to code it all in manually. I have a json file that looks like:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder",
"AOA": "Angolan Kwanza",
"ARS": "Argentine Peso",
"AUD": "Australian Dollar",
"AWG": "Aruban Florin",
...
}

I want to read that object one currency at a time so I can use it to populate the spinner. Something along the lines of:

/*PSEUDOCODE*/
spinner = (Spinner) findViewById(R.id.currencyTo);
List<String> list = new ArrayList<String>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
while (rates != null) {
rates = json.getString(first item in json);
list.add(rates);
...

I know how to do it by calling each item individually, such as rates = json.getString("AED") and so on, but I don't want it so hardcoded like that. I want to parse each currency item individually, then place it in the spinner. Grab the next currency, place it in the spinner, and so on and so forth. Any help is greatly appreciated.

anndruu12
  • 11
  • 3
  • http://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject – gpasci Mar 21 '13 at 00:31
  • Also http://stackoverflow.com/a/4407731/321697 – Kevin Coppock Mar 21 '13 at 00:35
  • I think there are incremental JSON parsers, but it's almost always better to parse JSON all at once. In particular you have the problem that "object" (dictionary/map) entries are not guaranteed to be in any particular order, so pretty much each access must scan the JSON from the start. – Hot Licks Mar 21 '13 at 00:44

1 Answers1

0

Yes, you can iterate through all the JSON elements.

Try this:

final JSONParser jParser = new JSONParser();
final JSONObject jObject = jParser.getJSONFromUrl(url);
Iterator<?> keys = jObject.keys();

while(keys.hasNext()){
    final String key = (String)keys.next();
    final Object obj = jObject.get(key);
    if(obj instanceof JSONObject){
        final String rate = jObject.getString(key);
        System.out.println(key + " => " + rate);
        list.add(rate);
    }
}
David Manpearl
  • 12,362
  • 8
  • 55
  • 72