Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject to ArrayList square brackets missing

I am trying to get the rates from https://api.ratesapi.io/api/latest into an ArrayList<Currency> of a custom Currency class:

public class Currency {
    private String shortName;
    private double rate;
    ...
}

The JSON looks like:

{"base":"EUR","rates":{"GBP":0.90033,"HKD":9.1786,"IDR":17304.0,
 "ILS":4.0309,"DKK":7.45,"INR":88.765,"CHF":1.0759,"MXN":26.615,
 "CZK":26.202,"SGD":1.6236,"THB":36.832,"HRK":7.468,"MYR":4.9604,
 "NOK":10.6538,"CNY":8.2325,"BGN":1.9558,"PHP":58.136,"SEK":10.3165,
 "PLN":4.4073,"ZAR":20.7655,"CAD":1.5748,"ISK":160.2,"BRL":6.334,
 "RON":4.836,"NZD":1.7828,"TRY":8.5853,"JPY":124.96,"RUB":86.9321,
 "KRW":1404.99,"USD":1.1843,"HUF":346.23,"AUD":1.6492},"date":"2020-08-06"}

Using org.json I managed to get the data into a JSONObject:

JSONObject obj = new JSONObject(getJSON("https://api.ratesapi.io/api/latest"));

As far as I understand, the normal procedure is now to convert the JSONObject into a JSONArray. However trying:

JSONArray jsonArray = obj.getJSONArray("rates");

fails with the error message:

Exception in thread "main" org.json.JSONException: JSONObject["rates"]
is not a JSONArray.

How do I fix this error or is there another way to make an ArrayList out of the JSON?

I suspect that the problem are missing square brackets in the JSON string.

like image 604
user1583209 Avatar asked Dec 17 '22 12:12

user1583209


1 Answers

If you take a look at the JSON returned by the API, you get a JSON object:

{"base":"EUR","rates":{"GBP":0.90033,"HKD":9.1786, ... },"date":"2020-08-06"}

You probably want to do something like this:

JSONObject obj = new JSONObject(getJSON("https://api.ratesapi.io/api/latest"));
JSONObject rates = obj.getJSONObject("rates");
final Iterator<String> keys = rates.keys();
while (keys.hasNext()) {
  final String key = keys.next();
  final Currency currency = new Currency(key, rates.getDouble(key));
  // do something with the Currency
}
like image 174
dpr Avatar answered Dec 20 '22 02:12

dpr