I'm using the code below to serialize the responses from the API into proper strings but I'm getting...
z
I'm using the code below to serialize the responses from the API into proper strings but I'm getting an error like this
Expected JsonPrimitive at text, found {"runs":[{"text":"All"}]}
I'm not sure what I'm doing wrong here
Copy code
internal typealias ApiText = @Serializable(ApiTextSerializer::class) String

private class ApiTextSerializer : KSerializer<String> {
    override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ApiText")

    override fun deserialize(decoder: Decoder): String {
        val input = decoder as JsonDecoder

        return input.decodeJsonElement().jsonObject["runs"]!!.jsonArray.joinToString(separator = "") {
            it.jsonObject["text"]!!.jsonPrimitive.content
        }
    }

    override fun serialize(encoder: Encoder, value: String) {
        throw RuntimeException("Serialization is not needed")
    }
}
r
The only exception I get when I execute your code is "Unexpected JSON token at offset 10: Expected beginning of the string, but got { at path" because he didn't find the correct Serializer. Does the Ktor client trigger the deserialization under the cover? One possible issue might be the typealias: From my understanding specifying the Serializer with a typealias only works when the value is wrapped in another class as its property. See https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#specifying-serializer-globally-using-typealias In this example the value is wrapped in the class "ProgrammingLanguage". You might be able to replace your typealias with a value class.
z
It should trigger the deserialization. value class wouldn't be ideal cause I can't use it directly as if it was a string
It works if I get rid of the typealias and instead add the Serializable annotation to the property, but I use this dozens of times and it would be a lot easier for just a typealias if it worked
r
To me it looks like typealiases and @Serializable doesn't work with primitive types such as String. Maybe because they are treated differently internally. So yeah, lots of limitations with that feature. You could create an issue ticket to support typealias for String as it may be seen as a bug. I don't have a better solution either than the aforementioned.
z
Yea, that's what I'm thinking too