Home > Software design >  How I can save values to hash map from api?
How I can save values to hash map from api?

Time:02-16

 try {
        String apikey = "-------";
        String url = "https://freecurrencyapi.net/api/v2/latest?apikey="   apikey   "&base_currency=USD";
        URL urlForGetRequest = new URL(url);
        String readLine = null;
        HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
        conection.setRequestMethod("GET");
        int responseCode = conection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conection.getInputStream()));
            StringBuffer response = new StringBuffer();
            while ((readLine = in.readLine()) != null) {
                response.append(readLine);
            }
            in.close();
            System.out.println(response.toString());
        } else {
            throw new Exception("Error in API Call");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

How I can save values from api to Hashmap List? Where key will be first worth (e.g "JPY") and value will be worth of "JPY" (E.G 115). I wanted to use Jackson lib, but I didn't find any information for how to do it. Under the context menu's new option on any project package.

Or you can create that POJO manually.

After creating this class you should create gson from json string like below:

Gson gson = new Gson();

// JSON string to Java object
Currencies currencies = gson.fromJson(response.toString(), Currencies.class);

Finally you have a meaningful object instance which you can use/manipulate easily as you wish.

  • Related