简体   繁体   English

如何在 Android Java 中处理来自 JSON 的关联数组

[英]How to process an associative array from JSON in Android Java

I am trying to process the JSON output from https://api.exchangeratesapi.io/latest in my Android app, which is returned in this format:我正在尝试在我的 Android 应用程序中处理来自https://api.exchangeratesapi.io/latest的 JSON 输出,该输出以这种格式返回:

{
  "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:我想使用 GSON 来处理这个 JSON,所以我添加了一个类 ExchangeRates 来接收数据:

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

These commands load the JSON into my ExchangeRates class:这些命令将 JSON 加载到我的 ExchangeRates 类中:

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.我知道我可以添加货币的静态列表,但我希望代码能够在以后添加时自动处理其他货币。

It turned out to be very simple, and yes, @ya379, a HashMap was part of the answer.结果证明非常简单,是的,@ya379,HashMap 是答案的一部分。 Given a HashMap data type, GSON will translate the associative array part of the JSON directly to a HashMap:给定 HashMap 数据类型,GSON 会将 JSON 的关联数组部分直接转换为 HashMap:

class ExchangeRates {
    private String base;
    private String date;
    private HashMap<String, Double> rates;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM