在我的应用程序中,我需要找到所有以usd为基数的国家的货币汇率。我得到了一个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中做到这一点。

最佳答案

刚刚测试了这个:

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

10-08 19:33