leandro
10/06/2020, 11:42 AM__type
and another called message
) from my api, modeled using Retrofit and a generic response such as NetworkResponse<MyResponse, ErrorResponse>
, in which the ErrorResponse
is the sealed class in question.
Analysing the returned type with the debugger shows me that my generic response is
UnknownError(error=kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')
JSON input: {"__type":"UserLambdaValidationException","message":"..."})
I’m using v1.0.0-RC, and unsure how to proceed.Vampire
10/06/2020, 12:00 PMtype
. If you use Json { classDiscriminator = "__type" }
it will probably work properlyleandro
10/06/2020, 12:11 PM('null')
anymore, but right now as (’UserLambdaValidationException
’)
. I probably wont be able to match all possible values of __type
, so maybe I could use an when()
expression with a custom KSerializer
? I have:
@Serializer(forClass = ErrorResponse::class)
object ErrorResponseSerializer : KSerializer<ErrorResponse> {
override val descriptor = ErrorResponse.serializer().descriptor
override fun deserialize(decoder: Decoder): ErrorResponse {
val surrogate = decoder.decodeSerializableValue(ErrorResponse.serializer())
return when (surrogate.__type) {
"UsernameExistsException" -> {
UserExistsErrorResponse(surrogate.message, surrogate.__type)
}
"UserNotFoundException" -> {
UserNotFoundErrorResponse(surrogate.message, surrogate.__type)
}
else -> {
UnknownErrorResponse(surrogate.message, surrogate.__type)
}
}
}
}
and that would fit my needs.
If I apply to my sealed class definition, as
@Serializable(with = ErrorResponseSerializer::class)
sealed class ErrorResponse {
@SerialName("message") abstract val message: String
@SerialName("__type") abstract val __type: String
}
then the app crashes with StackOverflowError. I assume I’m misusing something around
decoder.decodeSerializableValue(ErrorResponse.serializer())
but can’t figure out how to do itVampire
10/06/2020, 12:22 PM('UserLambdaValidationException')
?
Afair the discriminator by default has the FQCN.
So if your class is in a package it doesn't match.
But you can use @SerialName
on the class to configure the discriminator value.leandro
10/06/2020, 12:30 PMThe same message but with (‘UserLambdaValidationException’)?Exactly 😕 but I imagine there will always be a different
__type
that I haven’t modeled (I don’t have access to the server side). Would a custom Kserializer be a solution? how can I deserialize and inspect/compare values?Vampire
10/06/2020, 1:17 PMleandro
10/06/2020, 1:22 PMVampire
10/06/2020, 1:22 PMVampire
10/06/2020, 1:23 PMVampire
10/06/2020, 1:23 PMleandro
10/06/2020, 1:41 PMPaul Griffith
10/06/2020, 8:52 PMJsonContentPolymorphicSerializer
stub provided builtin that seems like it would fitPaul Griffith
10/06/2020, 8:53 PMleandro
10/07/2020, 7:47 AM