0

在我的应用程序中,我需要以美元为基础找到所有国家的货币汇率。我得到一个包含汇率的 json 作为输出。下面是 json。

{
"disclaimer": "Exchange rates",
"license": "Data sourced from various providers",
"timestamp": 1361055609,
"base": "USD",
"rates": {
"AED": 3.672869,
"AFN": 51.769999,
"ALL": 104.798751,
"AMD": 406.549996,
"ANG": 1.7887,
"AOA": 95.946132,
"ARS": 5.009655,
"AUD": 0.969258,
"AWG": 1.789967,
"AZN": 0.7847,
"BAM": 1.465127,
"BBD": 2,
"BDT": 78.95455,
"BGN": 1.465315,
"BHD": 0.376979,
"BIF": 1573.6325,
"BMD": 1,
"BND": 1.235676,
"BOB": 6.984993,
"BRL": 1.963769,
....
}
}

现在我需要将这些汇率提取到一个哈希图中,其中货币代码作为键,汇率作为值。我如何在 java 中做到这一点。

4

2 回答 2

1

刚刚测试了这个:

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import java.io.File;
import java.io.IOException;
import java.util.Map;

public class Parser {

    public static void main(String[] args) throws IOException {
        File input = new File("input.txt");
        Map<String, Object> jsonFileAsMap = new ObjectMapper().readValue(input, new TypeReference<Map<String, Object>>() {});

        Map<String, Object> ratesMap = (Map<String, Object>) jsonFileAsMap.get("rates");
        ratesMap.forEach((k, v) -> System.out.println("Key = " + k + ", Value = " + v));
    }
}

输出 :

Key = AED, Value = 3.672869
Key = AFN, Value = 51.769999
Key = ALL, Value = 104.798751
Key = AMD, Value = 406.549996
Key = ANG, Value = 1.7887
Key = AOA, Value = 95.946132
Key = ARS, Value = 5.009655
Key = AUD, Value = 0.969258
Key = AWG, Value = 1.789967
Key = AZN, Value = 0.7847
Key = BAM, Value = 1.465127
Key = BBD, Value = 2
Key = BDT, Value = 78.95455
Key = BGN, Value = 1.465315
Key = BHD, Value = 0.376979
Key = BIF, Value = 1573.6325
Key = BMD, Value = 1
Key = BND, Value = 1.235676
Key = BOB, Value = 6.984993
Key = BRL, Value = 1.963769

需要的库:

https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl/1.9.13 https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl/1.9.13

于 2016-11-04T12:23:46.057 回答
0

使用Jackson库进行转换 - 这非常简单。有关如何执行此操作的示例,请参见其他问题。

于 2016-11-04T11:45:40.440 回答