JsonFeature for Ktor Client is unresolved

Viewed 3396

I am starting Ktor based client in android and I want to use any of serializers, currently, the one from kotlinx but the result is the same for others - JsonFeature is not found (highlighted read in the snippet below). What am I missing?

class StreamClient {
    val client: HttpClient
    init {
        client = HttpClient(Android) {
            install(JsonFeature) {
                serializer = KotlinxSerializer()
            }
        }
    }
}

Gradle:

implementation("io.ktor:ktor-client-core:$ktor_version")
implementation("io.ktor:ktor-client-android:$ktor_version")
implementation("io.ktor:ktor-client-serialization:$ktor_version")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.0")
4 Answers

The client documentation for ktor 1.6.8 states that GSON or Jackson can be used in JVM and kotlinx.serialization can also be used for Multiplatform setups.

JsonFeature can be used to serialize/deserialize JSON data when sending requests and receiving responses. This functionality is provided for JVM by using the Gson/Jackson libraries and for Kotlin Multiplatform by using kotlinx.serialization.

https://ktor.io/docs/json.html

I was able to setup the serializer as follows:

val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
            prettyPrint = true
            isLenient = true
            ignoreUnknownKeys = true
        })
    }
}

with these dependencies

implementation("io.ktor:ktor-client-core:$ktor_version")
implementation("io.ktor:ktor-client-apache:$ktor_version")
implementation("io.ktor:ktor-client-serialization:$ktor_version")

As it was said it has been renamed in favor of ContentNegotiation

You have to add negotiation dependency:

implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")

Also, JSON

implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")

And install it under httpClient setup

install(ContentNegotiation) {
    json()
}

Details are available here: https://ktor.io/docs/serialization.html#register_json

All dependencies described in the Json documentation expose API of the ktor-client-json module that contains JsonFeature.

Related