Hey! I have a generic data class and I keep gettin...
# serialization
r
Hey! I have a generic data class and I keep getting this error:
Serializer for class 'GetPaginatedResponse' is not found
This is my data class
Copy code
@Serializable(with = GetPaginatedResponseSerializable::class)
data class GetPaginatedResponse(val isNext: Boolean, val content: T)
More info in 🧵
I have tried a custom serializer but it doesnt work
Copy code
class GetPaginatedResponseSerializable<T>(private val tSerializer: KSerializer<T>) : KSerializer<GetPaginatedResponse<T>> {

    private val paginatedResponseSerializer = GetPaginatedResponse.serializer(tSerializer)

    override val descriptor: SerialDescriptor
        get() = SerialDescriptor("GetPaginatedResponseSerializable", paginatedResponseSerializer.descriptor)

    override fun deserialize(decoder: Decoder): GetPaginatedResponse<T> {
        val paginatedResponse = decoder.decodeSerializableValue(paginatedResponseSerializer)
        val isNext = paginatedResponse.isNext
        val content = paginatedResponse.content

        return GetPaginatedResponse(
            isNext = isNext,
            content = content
        )
    }

    override fun serialize(encoder: Encoder, value: GetPaginatedResponse<T>) {
        encoder.encodeSerializableValue(paginatedResponseSerializer, GetPaginatedResponse(value.isNext, value.content))
    }
}
a
It looks like you're using the serializer recursively
The custom serializer class tries to fetch itself
Serializing generic content can be hard. What sort of values can the
content
property be? Primitives, or objects, or lists? Are the possible values ones you have declared yourself, or are they external?
r
It will mostly be lists. List<SomeType>
Yes they are declared by myself
a
Ah okay, that's good. It's generally easier to used closed-polymorphism instead of open-polymorphism. I'd create a
sealed interface
parent for your SomeType, and change GetPaginatedResponse so it's not generic, but instead just uses SomeTypeParent.
Copy code
@Serializable
data class GetPaginatedResponse(
  val isNext: Boolean,
  val content: SomeTypeParent,
)
Because SomeParentType is sealed, the possible values are limited, and KxS will be more easily able to encode/decode.
r
Okay and doing this will eliminate the need for custom serializer as well?