-1

Im trying to parse a json for an android app.

Its in this format:

"ticker_24h":{
  "total":{
     "last":24171.580293457908,
     "high":30808.7,
     "low":21159.009,
     "vol":864.2217252755704,
     "vwap":23665.865289000638,
     "money":20452554.930199366,
     "trades":6463
  },
  "exchanges":{
     "NEG":{
        "last":24500,
        "open":23125.08,
        "high":24630,
        "low":22850.04,
        "vol":431.26271897999953,
        "vwap":24037.00642046651,
        "money":10366264.745030094,
        "trades":1572
     },
     "MBT":{
        "last":23893.87002,
        "open":22880,
        "high":24161.57992,
        "low":22700,
        "vol":102.92291203000005,
        "vwap":23372.09484545152,
        "money":2405524.0617352244,
        "trades":1835
     }
   }    }

So far I have this but im getting a json parse error on logcat.

JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONObject ticker = jsonObj.getJSONObject("ticker_24h");
                JSONArray exchanges = ticker.getJSONArray("exchanges");

                // looping through All exchanges
                for (int i = 0; i < exchanges.length(); i++) {
                    JSONObject e = exchanges.getJSONObject(i);

                    String name = e.names().getString(i);
                    String price = e.getString("last");

                    // tmp hash map for single exchange
                    HashMap<String, String> exchange = new HashMap<>();

                    // adding each child node to HashMap key => value
                    exchange.put("name", name);
                    exchange.put("price", price);

                    // adding exchange to exchange list
                    exchangeList.add(exchange);
                }

Ideally i would need a string called name with each key name and a string called price with each "last" value from these keys.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

Try this code. I am using iterator to loop over the exchanges, the name of the exchange can be retrieved by iterator.next()

JSONObject exchanges = ticker.getJSONArray("exchanges");
 for (Iterator i = exchanges.keys(); i.hasNext(); ) {
  String keys = (String) i.next();
  Util.logRanjith("Exchange name is " + keys);
  JSONObject temp = (JSONObject) jsonObject.get(keys);
  String last=temp.get("last").toString();
}
Psypher
  • 10,717
  • 12
  • 59
  • 83