Home > Software engineering >  Android - How to create data class for response having dynamic keys?
Android - How to create data class for response having dynamic keys?

Time:09-12

How can I create data class for below response?

{
  "1843700": {
    "charge": "0.06600",
    "start_count": "463",
    "status": "Completed",
    "remains": "0",
    "currency": "USD"
  },
  "1843613": {
    "charge": "0.66000",
    "start_count": "1797",
    "status": "Completed",
    "remains": "0",
    "currency": "USD"
  }
}

I tried the below data class but it doesn't work. In retrofit I see the response in logs but the keys are not mapped to below data class.

@Keep
data class SMMOrdersResponse(
    val responseMap: Map<String, SMMOrdersMetadata>?
) : Serializable

@Keep
data class SMMOrdersMetadata(
    @SerializedName("charge") val charge: String?,
    @SerializedName("start_count") val startCount: String?,
    @SerializedName("status") val status: String?,
    @SerializedName("remains") val remains: String?,
    @SerializedName("currency") val currency: String?,
    @SerializedName("error") val error: String?
) : Serializable

CodePudding user response:

If your response doesn't contain a nested object called "responseMap", the mapping will not be performed.

Change SMMOrdersResponse data class like:

@Keep
class SMMOrdersResponse : LinkedHashMap<String, SMMOrdersMetadata>()

CodePudding user response:

Try this

data class Response(val product1: Item, val product2: Item)


 data class Item(
val charge: String,
val currency: String,
val remains: String,
val start_count: String,
val status: String 
)
  • Related