Skip to content Skip to sidebar Skip to footer

Json With Dynamic Keys While Using Retrofit In Android

I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to

Solution 1:

If you are using the Retrofit then you can directly parse this into some model let's say TestModel based on your requirement call something like this.

@GET("your endpoint")
Call<TestModel> getTestData();

and here you will get data

publicvoidgetTestData(){
    mApiServiceNetwork.getNetworkService(null,WebConstants.API_ENDPOINT)
            .getTestData()
            .enqueue(newCallback<TestModel>() {
                @OverridepublicvoidonResponse(final Call<TestModel> call, final Response<TestModel> response) {
                    if (response.code()==200){
                        //handle the responseTestModeltestModel= response.body();
                    }else{
                        //handle the error
                    }
                }

                @OverridepublicvoidonFailure(final Call<TestModel> call, final Throwable t) {

                }
            });
}

or

if you are getting data in JSON object then do like this.

private TestModel getTestModel(JsonObject jsonObject){
        Gsongson=newGson();
        TestModeltestModel= gson.fromJson(jsonObject,TestModel.class);
        return testModel;
    }

and if you are getting data in String then parse into Json object then call above method here is how you can convert string into json object.

JsonObjectjsonParser=newJsonParser().parse(json).getAsJsonObject();

and most important your TestModel should be like this below for both the cases.

publicclassTestModel {
@SerializedName("Meta Data")
@ExposeprivateMetaModel mMetaModel;

publicMetaModelgetMetaModel() {
    return mMetaModel;
}

publicvoidsetMetaModel(final MetaModel metaModel) {
    mMetaModel = metaModel;
}

publicMap<String, TimeModel> getTimeModel() {
    return mTimeModel;
}

publicvoidsetTimeModel(final Map<String, TimeModel> timeModel) {
    mTimeModel = timeModel;
}

@SerializedName("Time Series (1min)")

@ExposeprivateMap<String,TimeModel> mTimeModel;

publicstaticclassMetaModel{

    @SerializedName("1. Information")
    @ExposeprivateString _1Information;
    @SerializedName("2. Symbol")
    @ExposeprivateString _2Symbol;
    @SerializedName("3. Last Refreshed")
    @ExposeprivateString _3LastRefreshed;
    @SerializedName("4. Interval")
    @ExposeprivateString _4Interval;
    @SerializedName("5. Output Size")
    @ExposeprivateString _5OutputSize;
    @SerializedName("6. Time Zone")
    @ExposeprivateString _6TimeZone;

    publicStringget_1Information() {
        return _1Information;
    }

    publicvoidset_1Information(final String _1Information) {
        this._1Information = _1Information;
    }

    publicStringget_2Symbol() {
        return _2Symbol;
    }

    publicvoidset_2Symbol(final String _2Symbol) {
        this._2Symbol = _2Symbol;
    }

    publicStringget_3LastRefreshed() {
        return _3LastRefreshed;
    }

    publicvoidset_3LastRefreshed(final String _3LastRefreshed) {
        this._3LastRefreshed = _3LastRefreshed;
    }

    publicStringget_4Interval() {
        return _4Interval;
    }

    publicvoidset_4Interval(final String _4Interval) {
        this._4Interval = _4Interval;
    }

    publicStringget_5OutputSize() {
        return _5OutputSize;
    }

    publicvoidset_5OutputSize(final String _5OutputSize) {
        this._5OutputSize = _5OutputSize;
    }

    publicStringget_6TimeZone() {
        return _6TimeZone;
    }

    publicvoidset_6TimeZone(final String _6TimeZone) {
        this._6TimeZone = _6TimeZone;
    }
}
publicstaticclassTimeModel{
    @SerializedName("1. open")
    @ExposeprivateString _1Open;
    @SerializedName("2. high")
    @ExposeprivateString _2High;
    @SerializedName("3. low")
    @ExposeprivateString _3Low;
    @SerializedName("4. close")
    @ExposeprivateString _4Close;
    @SerializedName("5. volume")
    @ExposeprivateString _5Volume;

    publicStringget_1Open() {
        return _1Open;
    }

    publicvoidset_1Open(final String _1Open) {
        this._1Open = _1Open;
    }

    publicStringget_2High() {
        return _2High;
    }

    publicvoidset_2High(final String _2High) {
        this._2High = _2High;
    }

    publicStringget_3Low() {
        return _3Low;
    }

    publicvoidset_3Low(final String _3Low) {
        this._3Low = _3Low;
    }

    publicStringget_4Close() {
        return _4Close;
    }

    publicvoidset_4Close(final String _4Close) {
        this._4Close = _4Close;
    }

    publicStringget_5Volume() {
        return _5Volume;
    }

    publicvoidset_5Volume(final String _5Volume) {
        this._5Volume = _5Volume;
    }
}

}

the key point is if we give retrofit with Map<K,V> it will parse this into model automatically if the model is just like in JSON.

Solution 2:

If you want to manually parse JsonString, follow below code:

JSONObjectobject = newJSONObject(jsonString);
        Map<String, Object> metaDataMap = toMap(object.getJSONObject("Meta Data"));
        displayMap(metaDataMap);

        Map<String, Object> timeSeriesMap = toMap(object.getJSONObject("Time Series (1min)"));
        displayMap(timeSeriesMap);

toMap method:

publicMap<String, Object> toMap(JSONObjectobject) throws JSONException {
        Map<String, Object> map = newTreeMap<String, Object>();  // TreeMap(for getting data in sorted order[Ascending])Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceofJSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

displayMap method:

publicvoid displayMap(Map<String, Object> myMap) {
        Iteratoriterator = myMap.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mentry = (Map.Entry)iterator.next();
             System.out.println("key is: "+ mentry.getKey() + " & Value is: " + mentry.getValue());
        }
    }

OUTPUT:

key is:1.Information&Value is:Intraday(1min)pricesandvolumeskey is:2.Symbol&Value is:MSFTkey is:3.LastRefreshed&Value is:2017-12-01 16:00:00key is:4.Interval&Value is:1minkey is:5.OutputSize&Value is:Compactkey is:6.TimeZone&Value is:US/Easternkey is:2017-12-01 15:58:00&Value is: {1.open=84.2800, 2.high=84.3000, 3.low=84.2400, 4.close=84.2550, 5.volume=139520}
key is:2017-12-01 15:59:00&Value is: {1.open=84.2500, 2.high=84.2600, 3.low=84.2000, 4.close=84.2000, 5.volume=175169}
key is:2017-12-01 16:00:00&Value is: {1.open=84.2000, 2.high=84.2600, 3.low=84.1800, 4.close=84.2000, 5.volume=3311341}

Solution 3:

I think this might help you:

JSONObject timeJsonObject = mainObject.getJSONObject("Time Series (1min)");



    Iterator<String> keysItr = timeJsonObject.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();

        //now here you get key as : 2017-12-01 16:00:00//do here code as:JSONObject individualObject = timeJsonObject.getJSONObject(key);

        String openTime = individualObject.getString("1. open");
        String highTime = individualObject.getString("1. high");
        String lowTime = individualObject.getString("1. low");
        String closeTime = individualObject.getString("1. close");
        String volumeTime = individualObject.getString("1. volumne");


    }

Here "while-loop" iterates for all keys for "2017-12-01 16:00:00,2017-12-01 15:59:00,2017-12-01 15:58:00" and so on. It will iterate for how many keys will added in this section.

Post a Comment for "Json With Dynamic Keys While Using Retrofit In Android"