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
{
"1":"abc",
"2","abc",
"3":"abc",
"4","abc"
}

case 2
{
"5":"abc",
"6","abc",
"7":"abc",
"8","abc"
}

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

KeyValueModel.java

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)iteratorObj.next();
       String valueName=jsonResponse.getString(keyName);
       KeyValueModel keyValueModel=new KeyValueModel(keyName,valueName);
       responseList.add(keyValueModel);
     }

Now you can access your response from responseList

No comments:

Post a Comment