Bhuvi Bhuvi -4 years ago 225
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download