I’m trying to set up Ktor with exposed and I can’t...
# serialization
d
I’m trying to set up Ktor with exposed and I can’t figure out how to serialize my model. I have
Copy code
object Cars: IntIdTable() {
    val name = varchar("name", 128)
    val year = integer("year")
}

class Car(id: EntityID<Int>): IntEntity(id) {
    companion object : IntEntityClass<Car>(Cars)
    var name by Cars.name
    var year by Cars.year
}

//@Serializable
class SerializedCar(id: EntityID<Int>, name: String, year: Int): IntEntity(id)
then :
Copy code
class CarDAO {
    private fun resultRowToCar(row: ResultRow) = SerializedCar(
        id = row[Cars.id],
        name = row[Cars.name],
        year = row[Cars.year]
    )

    suspend fun show(id: Int): SerializedCar? = transaction {
        Cars
            .select { Cars.id eq id }
            .map(::resultRowToCar)
            .singleOrNull()
    }
}
and my route is :
Copy code
get("/cars/{id}") {
            val id = call.parameters.getOrFail<Int>("id").toInt()
            call.respond(mapOf("car" to carDAO.show(id)))
        }
but I get this error :
Copy code
500: kotlinx.serialization.SerializationException: Serializer for class 'SerializedCar' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
You can see the project here for more info:
Copy code
<https://github.com/danygiguere/ktor-kotlin-example>
And if I uncomment
//@Serializable
, my IDE tells me :
Impossible to make this class serializable because its parent is not serializable and does not have exactly one constructor without parameters
h
You can't inherit from Exposed Entity class, because it is not serializable by default. Instead remove its parent and use this definition:
Copy code
@Serializable
data class SerializedCar(id: Int, name: String, year: Int)
Alternative you could write your custom serializer for
Car
by yourself.
👍 1