Search code examples
jsonapikotlinretrofit

Long response from retrofit - can I make my model class more optimized?


I have response some retrofit, and I'd like to ask you, if there's some way to make the model class shorter.

So the response look like this:

"qwe"{
  "X": {
        "start_rate": 3.3,
        "end_rate": 2.2,
        "change": -1.1,
        "change_pct": -9.9
    },
    "XX": {
        "start_rate": 1.1,
        "end_rate": 2.2,
        "change": 3.3,
        "change_pct": 4.4
    },
    "XXX": {
        "start_rate": 6.6,
        "end_rate": 5.5,
        "change": 6.6,
        "change_pct": 33.3
    }
}
...

As you can see the object names are different, and it will be repeated over 170 times. Since I'd like to get the value of change inside of every object, I have to call that object first. Is there any way to make less boilerplate code, or I need to make something like this, for every single one object?:

data class qwe(
@SerializedName("X")
val xVal: X
)

data class X(
@SerializedName("start_rate")
val startRate: Double,

@SerializedName("end_rate")
val endRate: Double,

@SerializedName("change")
val change: Double,

@SerializedName("change_pct")
val changePct: Double
)

Solution

  • If the keys in the qwe object are not "well-known" in advance, but depend on whatever you get at runtime, it is closer to a Kotlin Map rather than a class with properties.

    You could try to replace the usage of your qwe class with a Map<String, X> where X is your class representing the nested objects.

    data class WhateverWrapperYouAreUsing(
        val qwe: Map<String, X>,
    )
    
    data class X(
        @SerializedName("start_rate")
        val startRate: Double,
    
        @SerializedName("end_rate")
        val endRate: Double,
    
        @SerializedName("change")
        val change: Double,
    
        @SerializedName("change_pct")
        val changePct: Double
    )