如何将国家名称转换为货币代码?

时间:2016-11-11 11:29:11

标签: java android

假设我的国家/地区名称为USA。所以我想转换为USD。我只有来自webservice的国家/地区名称。

我已尝试过此代码,但如何将国家/地区名称转换为Locale对象。有人可以在这个问题上提出建议吗?

String countryName=jsonObject.getString("country");

2 个答案:

答案 0 :(得分:3)

提供国家/地区代码而非国家/地区名称

public static void main(String[] args) throws InterruptedException {
Map<String, String> countries = new HashMap<>();
for (String iso : Locale.getISOCountries()) {
    Locale l = new Locale("", iso);
    countries.put(l.getDisplayCountry(), iso);
}

System.out.println(countries.get("Switzerland"));
System.out.println(countries.get("Andorra"));
System.out.println(countries.get("Japan"));
 }

答案 1 :(得分:2)

您还可以使用专为此目的而设计的https://github.com/TakahikoKawasaki/nv-i18n库。

从其GitHub页面

  

支持国际化的包,包含ISO 3166-1国家/地区   代码枚举,ISO 639-1语言代码枚举等

此问题的具体示例

String countryName = jsonObject.getString("country");
List<CurrencyCode> codes = CurrencyCode.getByCountry(countryName, false)

查看可用列表的简单示例(来自Github页面),

// List all the currency codes.
for (CurrencyCode code : CurrencyCode.values())
{
    System.out.format("[%s] %03d %s\n", code, code.getNumeric(), code.getName());
}

// List all the country codes.
for (CountryCode code : CountryCode.values())
{
    System.out.format("[%s] %s\n", code, code.getName());
}