Ktor Serializer isn't seen by Android Studio (Serializer for class 'User' is not found.)

Viewed 1063

I'm trying to use Ktor in my project. I made everything as it's written in documentation, but it doesn't work

Dependencies:

implementation "io.ktor:ktor-client-core:1.5.4"
implementation "io.ktor:ktor-client-android:1.5.4"
implementation "io.ktor:ktor-client-serialization-jvm:1.5.4"

HTTPClient and request:

val client = HttpClient {
    install(JsonFeature){
        serializer = KotlinxSerializer()
    }
    defaultRequest {
        url {
            protocol = URLProtocol.HTTPS
            host = "testtesttest.zapto.org"
        }
    }
}

suspend fun getUsersList() = client.get<User>{
    url("/users/list")
}

User class:

import com.kepler88d.icthack2app.model.enumerations.UserSpecialization
import kotlinx.serialization.Serializable

@Serializable
data class User(
    val id: Int,
    val password: String,
    val rating: Float,
    val specialization: UserSpecialization,
    val firstName: String,
    val lastName: String,
    val profileDescription: String,
    val githubProfileLink: String,
    val projectIdList: MutableList<Int>,
    val replyIdList: MutableList<Int>,
    val tgId: String,
)

UserSpecialization class:

import kotlinx.serialization.Serializable

@Serializable
enum class UserSpecialization {
    IOS_DEVELOPER, ANDROID_DEVELOPER, WEB_BACKEND_DEVELOPER, WEB_FRONTEND_DEVELOPER
}

When i'm trying to deserialize JSON into object it crashes with this error:

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

The strange thing is that the enum class Android studio see as serializable, but data class doesn't

enum class data class

2 Answers

The solution was to add plugin

id 'kotlinx-serialization'

I did this for Android but it may also work for ktor. At first, add this line to dependencies in the build project gradle:

classpath "org.jetbrains.kotlin:kotlin-serialization:1.5.21"

Add also these to the build app gradle:

plugins {
    ...
    id 'kotlinx-serialization'
}
dependencies {
    ...
    implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2'
}

Please note version numbers might be different.

Related