Bhuvi Bhuvi - 24 days ago 14
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?

Answer

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)keys.next();

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

    // do your more stuff here
}
Comments