getting values from a Gson object into a HashMap

Viewed 187

I have the following json String:

"{\"rates\":{\"CAD\":1.5601,\"HKD\":8.4781,\"ISK\":156.1,\"PHP\":55.709,\"DKK\":7.4642,\"HUF\":369.36,\"CZK\":27.369,\"AUD\":1.8053,\"RON\":4.834,\"SEK\":10.9368,\"IDR\":18239.61,\"INR\":83.6004,\"BRL\":5.7349,\"RUB\":86.475,\"HRK\":7.6285,\"JPY\":117.55,\"THB\":36.111,\"CHF\":1.0564,\"SGD\":1.5689,\"PLN\":4.5815,\"BGN\":1.9558,\"TRY\":7.2925,\"CNY\":7.7653,\"NOK\":11.2685,\"NZD\":1.8547,\"ZAR\":19.6619,\"USD\":1.0936,\"MXN\":26.4097,\"ILS\":3.9015,\"GBP\":0.8846,\"KRW\":1346.48,\"MYR\":4.7654},\"base\":\"EUR\",\"date\":\"2020-04-01\"}"

it's a list of rates with the matching rate values, these have been retrieved from here.

What I want to do, is to deserialize the string into an object, that I've already created

package com.example.android.myrates.core.json;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class JsonLatestStructure {

    @SerializedName("rates")
    @Expose
    private JsonRatesStructure rates;
    @SerializedName("base")
    @Expose
    private String base;
    @SerializedName("date")
    @Expose
    private String date;

    public JsonRatesStructure getRates() {
        return rates;
    }

    public void setRates(JsonRatesStructure rates) {
        this.rates = rates;
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}

I currently have a method that creates a new Gson object, and I want to be able to get all the rate names and matching rate values into a hashmap.

JsonLatestStructure jsonData = new Gson().fromJson(rateListPresenter.getLatestRateList(), JsonLatestStructure.class);

Thanks in advance!

UPDATE:

I accomplished what I wanted by doing this:

JsonLatestStructure jsonData = new Gson().fromJson(rateListPresenter.getLatestRateList(), JsonLatestStructure.class);

Map<String, Double> rateListItems = jsonData.getRates();
1 Answers

Try below it will return all dynamic key and value list

JSONObject data = jsonResponse.getJSONObject("rates");// here response is server response
    Iterator keys = data.keys();

    while(keys.hasNext()) {
        // loop to get the dynamic key
        String key = (String)keys.next();  // it returns a key ;ile CAD, HKD etc...

        // get the value of the dynamic key
        int value = data.getInt(key);      // it returns a value like 1.5601,8.4781 etc...

    }
Related