Converting messy API response to Kotlin Data class

42 Views Asked by At

I have an andorid app for Labeling map.I use an API to retrive user previuse map labels. this labels could be a triangle with 3 coordinate pointe or huge polygen with more than 30 coordinate points. my API response is like : Response<MapLabels> and my **MapLabels **data class is :

class MapLabels : ArrayList<MapLabelsItem?>()

data class MapLabelsItem(
    val coordinate: MapCoordinate,
    val created_at: String,
    val file_id: Int,
    val id: Int,
    val label: Label,
    val label_id: Int,
    val status: Any,
    val updated_at: String,
    val user_id: Int
)

data class Label(
    val category_id: Int,
    val created_at: String,
    val description: Any,
    val id: Int,
    val name: String,
    val translate: String,
    val updated_at: String,
    val user_id: Int
)

data class MapCoordinate()

problem is with data class of MapCooedinate

casuse my response if coordinate is unknown number of parameters with type of 'x','y','lat','lng'and this is not sorted and we could sort it cause of overloading of backend processing. my sample json response in part of coordinate is like :

{"x1":"605","x2":"412","x3":"722","x4":"687","x5":"365","y1":"283","y2":"88","y3":"116","y4":"339","y5":"414","lat1":"35.739907251776","lat2":"35.743303435154","lat3":"35.742815786961","lat4":"35.738931910799","lat5":"35.737625631846","lng1":"51.419249096613","lng2":"51.415104497685","lng3":"51.421759144197","lng4":"51.421007813139","lng5":"51.414095567407"}

and i repeat that it is well sorted cause it have just 5 point and if we had more that 9 point It will be messy.

I had tried to parse json mannually to data class but it was hard to me and i failed. i expect to have some better wat to parse it correctly and need to know is there any shore appropriate way

1

There are 1 best solutions below

1
damienG On

Maybe it will help you to make some progress. It should make key-value pair which should be easier to handle

@JsonAdapter(MapCoordinateCustomAdapter::class)
data class MapCoordinate(
var coordinates: MutableMap<String, String> = mutableMapOf())

class MapCoordinateCustomAdapter: JsonDeserializer<MapCoordinate> {
override fun deserialize(
    json: JsonElement?,
    typeOfT: Type?,
    context: JsonDeserializationContext?): MapCoordinate {
    val mapCoordinates: MapCoordinate = MapCoordinate()

    json?.let {
        val jsonObject = it.asJsonObject
        jsonObject.entrySet().forEach { entry -> 
            mapCoordinates.coordinates[entry.key] = entry.value.asString
        }
    }
    return mapCoordinates
}}