Search code examples
androidretrofitpojo

How to write a Pojo using a dynamic key inside JSONarray


I don't even know if this is a valid question but I am having a hard time converting the API result to POJO since some key are dynamic.

{
"data": [{
        "something_edit": true
    },
    {
        "test_null": false
    }
],
"success": true

}

As you can see the key inside data are dynamic. I tried using jsonschema2pojo or other converter but it is declaring a named variable which is not a good result. BTW I am using retrofit and GSON library

EDIT:

So here is the flow, so the keys are the ones I asked on the API. So for Example I asked something_edit1, something_edit2 and something_edit3. The data result will be.

{

"data": [{
        "something_edit1": true
    }, {
        "something_edit2": false
    },
    {
        "something_edit3": false
    }
],

"success": true
}

Solution

  • You can use Json Object or Generics for your condition.

    Using Json Object you can check, if key is exist in your json.

    if(yourJsonObject.hasOwnProperty('key_name')){
       // do your work here
    }
    

    Using Generic you have to check, if your Pojo have instance of the Pojo.

    if(YourMainPOJO instanceOf YourChildPojo){
       // do your work here
    }
    

    Try to view only Generic part in this link.