2

I am not sure if it is possible yet but i would like to serialize the following class.

@Serializable
sealed class RestResponseDTO<out T : Any>{
    @Serializable
    @SerialName("Success")
    class Success<out T : Any>(val value: T) : RestResponseDTO<T>()

    @Serializable
    @SerialName("Failure")
    class Error(val message: String) : RestResponseDTO<String>()
}

when i try and use it

route(buildRoute(BookDTO.restStub)) {
    get {
        call.respond(RestResponseDTO.Success(BookRepo.getAll()))
    }
}

I get this error:

kotlinx.serialization.SerializationException: Serializer for class 'Success' is not found. Mark the class as @Serializable or provide the serializer explicitly.

The repo mentioned in the get portion of the route returns a list of BookDTO

@Serializable
data class BookDTO(
    override val id: Int,
    override val dateCreated: Long,
    override val dateUpdated: Long,
    val title: String,
    val isbn: String,
    val description: String,
    val publisher:DTOMin,
    val authors:List<DTOMin>
):DTO {
    override fun getDisplay() = title
    companion object {
        val restStub = "/books"
    }
}

This problem is not a deal breaker but it would be great to use an exhaustive when on my ktor-client.

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
Chris Legge
  • 739
  • 2
  • 9
  • 24

1 Answers1

1

Serializing sealed classes works just fine. What is blocking you are the generic type parameters.

You probably want to remove those, and simply use value: DTO. Next, make sure to have all subtypes of DTO registered for polymorphic serialization in the SerializersModule.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161