Search code examples
androidjsonjsonschema2pojo

how to create a pojo class with dynamic key for arrayname


I am working with Rxandroid and retrofit. I have a json with dynamically changing array name like this,

{
  "2016-10-02": [
    {
      "name": "foo",
      "id": "1",
      "category": "bar"

    },
    {
     "name": "foo",
      "id": "2",
      "category": "bar"
    },
    {
     "name": "foo",
      "id": "3",
      "category": "bar"
    },
    {
      "name": "foo",
      "id": "4",
      "category": "bar"
    }
  ],
  "2016-10-01": [
    {
      "name": "foo",
      "id": "5",
      "category": "bar"
    },
    {
      "name": "foo",
      "id": "6",
      "category": "bar"
    },
  ],
 "2016-10-03": [
    {
      "name": "foo",
      "id": "5",
      "category": "bar"
    }
  ]
}

The date key name for each array changes automatically and the number of array changes. In this example there are 3 arrays with date key. But the number of these array varies.

I have been through various links in stackoverflow but could not solve the issue.


Solution

  • Use JSONObject keys() to get the key and then you could iterate each key to get the dynamic values :

        JSONObject object = new JSONObject("your response string")
        Iterator keys = object.keys();
    
        //Let's consider your POJO class is CategoryClass
        // Let's take HashMap to store your POJO class for specific KEY
        HashMap<String, ArrayList<CategoryClass>> mMap = new HashMap<String, ArrayList<CategoryClass>>();
    
        while(keys.hasNext()) {
            // here you will get dynamic keys
            String dynamicKey = (String)keys.next();
    
            // get the value of the dynamic key
            JSONArray dynamicValue = object.getJSONArray(currentDynamicKey);
    
            //Let's store into POJO Class and Prepare HashMap.
             ArrayList<CategoryClass> mCategoryList = new ArrayList<CategoryClass>();
             for(int i = 0 ; i < dynamicValue.length(); i++){
    
                 CategoryClass mCategory = new CategoryClass();
                 mCategory.setName(dynamicValue.getString("name"));
                 mCategory.setId(dynamicValue.getString("id"));
                 mCategory.setCategory(dynamicValue.getString("category"));
    
                 mCategoryList.add(mCategory);
    
    
             }
            //Add Into Hashmap
            mMap.put(dynamicKey, mCategoryList);
    
        }