0

In my application i need to find the currency exchange rates of all countries with usd as base.I got a json as the output which contains the exchange rates.Below is the 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,
....
}
}

Now i need to extracts these rates into a hashmap where the currency code as the key and exchange rate as value.How can i do that in java.

KJEjava48
  • 1,779
  • 4
  • 26
  • 58

2 Answers2

1

Just tested this :

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));
    }
}

Output :

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

Needed libraries :

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

Sorin J
  • 462
  • 1
  • 4
  • 14
  • But from where this input.txt file comes?? And where is my json string – KJEjava48 Nov 04 '16 at 12:33
  • input.txt is a file (created in the prj working directory) containing the JSON message you've posted. I assumed you are reading that message from a file. If not, you can use directly a String instead of that File object. – Sorin J Nov 04 '16 at 12:36
0

Use the Jackson library to do the conversion - it's pretty straightforward. See this other question for an example of how to do it.

Community
  • 1
  • 1
hebenon
  • 16
  • 2