I want to get the currency's from Json using Gson but my method returns null. The currency value should be a BigDecimal object and I want to get the value using currency symbol as method argument.
I've created a method rateFromApi(String currency) shown below. I've read the API and from what I understood the line
rate = rootObj.get(currency).getAsBigDecimal();
should assign to variable rate the value to which currency name is mapped. I found similar problem already here But still I do not understand what am I doing wrong in my code.
//fields and method in class responsible for getting data from Json
private final String sURL = "http://data.fixer.io/api/latest?access_key...";
private URL url = new URL(sURL);
private URLConnection request = url.openConnection();
private JsonParser jp = new JsonParser();
public BigDecimal rateFromAPI(String currency) throws IOException {
request.connect();
BigDecimal rate;
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootObj = root.getAsJsonObject();
return rate = rootObj.get(currency).getAsBigDecimal();
}
//expression in method main
//indicate which exactly currency has to be taken from Json
Zloty pln1 = eur.convertToPln(ratesGetter.rateFromAPI("PLN"));
I thought the Json will be parsed and by using the line rootObj.get(currency).getAsBigDecimal();
the value which is mapped to the currency name will be assigned to variable rate as BigDecimal but the result I'm getting is NullPointerException in return line.