Hey guys, I am working with an API that either returns a success response or an error response (both HTTP 200). They are 2 different JSON. How would I deserialize this using Kotlinx Serialization and Ktor? Would like to deserialize this into a sealed class like so:
Copy code
sealed class ApiResponse {
data class Success(val fields: String) : ApiResponse()
data class Error(val errorCode: String, val errorMessage: String): ApiResponse()
}
Is there any tutorial on how to do something like this?
j
Javier
08/19/2021, 10:52 AM
Search for polymorphism serialization in the serialization docs
n
Nikky
08/19/2021, 7:56 PM
do they have something like a
type
field for success or error ? maybe you can get away with a sealed class..
or just decode into a
JsonElement
and decide which serializer to use in a
when
you can try a
JsonTransformingSerializer
to preprocess the json
a
Ashley Figueira
08/20/2021, 2:07 PM
Dont think polymorphism would work since it doesn’t have any common field. Its completely different JSON response.
j
Javier
08/20/2021, 2:12 PM
Not sure, he can try by using that sealed class directly, marking it as serializable