0
I am using the exchangerate API (https://www.exchangerate-api.com) to pick up the currency quotes of the day.
Using the code below I get a Jsonobject containing the "rates":
private JsonObject getExchangesRate() throws JsonIOException, JsonSyntaxException, IOException {
// Setting URL
String url_str = "https://v3.exchangerate-api.com/bulk/f75b7f1b080c9060121e6754/BRL";
// Making Request
URL url = new URL(url_str);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to JSON
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject jsonobj = root.getAsJsonObject();
// Accessing object
return jsonobj;
}
Theoretically, it’s supposed to come in this format:
{
"result": "success",
"from": "USD",
"rates": {
"AUD": ((AUD in terms of USD)),
"BGN": 1.8096,
"BRL": 3.1143,
"...": 1.3113,
"...": 7.473, etc. etc.
}
}
I am trying to take the values inside the key "rates" and store the values of USD, EUR and GBP.
But I’m not getting it. I read about how JSON works in Java but I’m still not able to do what I want.
JsonObject resultadoJSON = getExchangesRate();
JsonElement rates = resultadoJSON.get("rates");
double ValorUSD = (double) rates.get("USD"); //Sei que não é assim, mas é o que to tentando fazer
double ValorEUR = (double) rates.get("EUR"); //Sei que não é assim, mas é o que to tentando fazer
Possible duplicate of How to convert JSON to Object and find an id (No Array) - JAVA
– StatelessDev
Also check How to convert JSON to Object and find an id - JAVA.
– Lucas Duete