Reputation: 455
I am trying to get a response from api and the Serialization it's not working, but it made the exactly the same with others data classes and they worked.
I am using ChangeFieldValueRequest data class as body to send with the request, as body, but i am receiving this message:
Failure(kotlinx.serialization.SerializationException: Serializer for class 'ChangeFieldValueRequest' is not found. Mark the class as @Serializable or provide the serializer explicitly.)
@Serializable
data class ChangeFieldValueRequest<T>(
@SerialName("commercial_premise_id") val commercialPremiseId: Int,
val field: String,
val value: T
)
data class response
package com.quicktendr.mgmt.shared.domain
import kotlinx.serialization.Serializable
@Serializable
data class StatusResponse(
val status: String,
val error: String?
)
request:
suspend fun <T> updateLocalField(
token: String, body: ChangeFieldValueRequest<T>
): StatusResponse {
val request = handleError<StatusResponse> {
httpClient.post("${baseUrl}api/management/updateLocalField") {
this.body = body
headers.append(HttpHeaders.ContentType, ContentType.Application.Json)
headers.append("Authorization", "Bearer $token")
}
}
when (request) {
is ApiResult.Success -> {
return request.value
}
is ApiResult.Error -> throw request.throwable
}
}
protected val httpClient: HttpClient = ServiceLocator.provideKtorHttpClient()
fun provideKtorHttpClient(): HttpClient {
if(ktorHttpClient == null) {
ktorHttpClient = HttpClient(generatePlatformHttpEngine()) {
install(JsonFeature) {
serializer = KotlinxSerializer(Json {
encodeDefaults = true
ignoreUnknownKeys = true
isLenient = true
})
accept(ContentType.Application.Json)
}
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.ALL
}
}
}
return ktorHttpClient!!
}
gradle cofiguration :
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
...
}
// kotlinx.serialization
private const val ktxSerializationVersion = "1.0.1"
// ktor
private const val ktorVersion = "1.4.2"
val ktxSerializationJson = "org.jetbrains.kotlinx:kotlinx-serialization-json:$ktxSerializationVersion"
val ktorSerialization = "io.ktor:ktor-client-serialization:$ktorVersion"
I have to send this on body:
{
"commercial_premise_id": 95,
"field":"delivery_paused",
"value": true
}
And the response body will be this:
{
"status": "ok",
"error": null
}
Upvotes: 3
Views: 1978
Reputation: 565
You may miss the plugin org.jetbrains.kotlin.plugin.serialization
:
plugins {
id("org.jetbrains.kotlin.plugin.serialization")
...
}
Upvotes: 2