Robert Munro
05/31/2021, 10:37 AM@Serializable
data class ResponseDomain constructor(
val payload: List<Domain> = listOf(),
val errors: List<ErrorDomain> = listOf()
)
where domain is a kotlin interface that all the domain data obects implement and they are serialized using kotlin serialization(polymorphic)
In my frontend I fetch the url like so:
val response = window
.fetch("$BASE_URL/playlists")
.await()
.json()
.await()
which has a payload of List<PlaylistDomain>
@Serializable
data class PlaylistDomain constructor(
val id: Long? = null,
val title: String,
val items: List<PlaylistItemDomain> = listOf(),
...
) : Domain
but casting back to ResponseDomain fails
(response as ResponseDomain)
with and Illegal cast
error
should i just send the response as text/plain (not application/json) and use kotlin deserialisation to get a ResponseDomain?
seems like since the browser parses my json to json object i seem to not be able to cast to my kotlin object type - obvs i dont want to map the whole thing from json to domain manually but in the kotlin js tutorial (the video browser one) they map the response as a cast (response as Video
). maybe it only works for simple objects?Robert Munro
05/31/2021, 11:14 AMval response = window
.fetch("$BASE_URL/playlists")
.await()
.text()
.await()
deserialiseResponse(response).let {
it.payload as List<PlaylistDomain>
}
if anyone has options on wearther or not this is the best way then i would be interested to know 🙂Robert Jaros
05/31/2021, 2:22 PM