Bhuvi Bhuvi - 4 months ago 42
JSON Question

Parsing json data with random keys(keys not staying the same throughout)

How can i parse below json data with inconsistent keys inside data object?The key names 2016 and 2015 are not fixed and are random .There can be more arrays inside data object with random key names.Can i create a model class with such json data?Can i use gson with this?


You can't make model with unknown keys. If you wanna make model then you have to know keys name. Yes, you can read dynamic json like this

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

while(keys.hasNext()) {
    // loop to get the dynamic key
    String key = (String);

    // get the value of the dynamic key
    JSONArray value = data.getJSONArray(key);

    // do your more stuff here