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.

3
  • Have you though about a custom deserializer? Commented Mar 10, 2020 at 12:04
  • Here is a similar solution on StackOverflow. Commented Mar 10, 2020 at 12:11
  • Could'nt you use a HashMap? Commented Mar 10, 2020 at 12:14

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.