Dedicated Server

How to parse json with unknown key in android ?

We might have come across json responses which are having unknown key names. For example, a single response may output different key names when invoked different times. In this case we may not know the key value before hand so that we could parse it using the key name. In such case we should first get all the key values into a list of key names and then iterate over the key names one by one.

For example if a single endpoint(api request) gives two responses during two cases like below

case 1

case 2

You could make use of Iterator for looping through the list of key names.

Create a model class for saving the key and value pair like below

public class KeyValueModel {
    String keyName;
    String valueName;

    public KeyValueModel(String keyName, String valueName) {
        this.keyName = keyName;
        this.valueName = valueName;

    public String getKeyName() {
        return keyName;

    public String getValueName() {
        return valueName;

Suppose you have a json response jsonObjectResponse(string). Then parse it like following

JSONObject jsonResponse = new JSONObject(jsonObjectResponse);
Iterator  iteratorObj = jsonResponse.keys();
ArrayList<KeyValueModel> responseList=new ArrayList<KeyValueModel>();
while (iteratorObj.hasNext())
       String keyName = (String);
       String valueName=jsonResponse.getString(keyName);
       KeyValueModel keyValueModel=new KeyValueModel(keyName,valueName);

Now you can access your response from responseList

No comments:

Post a Comment