0

I am trying to process the JSON output from https://api.exchangeratesapi.io/latest in my Android app, which is returned in this format:

{
  "rates": {
    "CAD": 1.5613,
    "HKD": 8.9041,
    ...
    "KRW": 1374.71,
    "MYR": 4.8304
  },
  "base": "EUR",
  "date": "2020-03-09"
}

I would like to use GSON to process this JSON, so I have added a class ExchangeRates to recieve the data:

class ExchangeRates {
    private String base;
    private String date;
}

These commands load the JSON into my ExchangeRates class:

Gson gson = new Gson();
ExchangeRates mExchangeRates = gson.fromJson(result, ExchangeRates.class);

However, I cannot figure out how to load the associative array of exchange rates into the class in a scalable manner. I know I could add a static list of the currencies, but I want the code to be able to automatically handle additional currencies if they are added at a later date.

jon
  • 3,202
  • 3
  • 23
  • 35

1 Answers1

0

It turned out to be very simple, and yes, @ya379, a HashMap was part of the answer. Given a HashMap data type, GSON will translate the associative array part of the JSON directly to a HashMap:

class ExchangeRates {
    private String base;
    private String date;
    private HashMap<String, Double> rates;
}
jon
  • 3,202
  • 3
  • 23
  • 35