skip to Main Content

I have used retrofit as calling API in android,

And I am getting response like this.

{
  "data": {
    "garden": {
      "id": "31",
      "name": "Garden",
      "count": 307
    },
    "balcony": {
      "id": "32",
      "name": "balcony",
      "count": 451
    },
    "Parking": {
      "id": "1",
      "name": "Parking",
      "count": 791
    },
    ...
  }
}
  • Here the data is in the form of object
  • And inside it garden, balcony, parking etc. are also in the form of objects.

Challange is

"garden":{...},"balcony":{...},"Parking":{...}

I have to show all this in the form of a list.

And the big challenge is that -> I will not know how many other objects like garden, balcony, parking etc will come in response.

If "data" had come in the form of a JSONArray, I would have been able to handle it by building some logic, but here "data" is a JSONObject.

How can I solve this? please help

What have I tried?

Fetched data as a String Like…

@SerializedName("data") val data: String,

But it is throwing a failure, Error: and it is saying that you are asking for a string, but "data" is an object.

Second, got the "data" fetched as a JSONObject Like…

@SerializedName("data") val data: JSONObject,

Yes, it is working, but when I am printing logs of the "data", I am getting empty JSONObject like.

"data" : {}

This is code that can handle the response, but it is not useful

data class MainData(
    @SerializedName("data") val data: Facilities,
)

data class Facilities(
    @SerializedName("garden") val garden: FacilitiesData,
    @SerializedName("balcony") val balcony: FacilitiesData,
    @SerializedName("parking") val parking: FacilitiesData,
    ...
)

data class FacilitiesData(
    @SerializedName("id") val id: Int? = 0,
    @SerializedName("name") val name: String? = "",
    @SerializedName("count") val count: Int? = 0,
)

2

Answers


  1. You should be able to define a response class like this

    data class MyResponse(val Map<String, FacilitiesData>)
    

    Then you can access each FacilitiesData item via its string key

    Login or Signup to reply.
  2. You can parse like…

    @SerializedName("data")
        @Expose
        private Map<String, Vitals> result;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search