https://kotlinlang.org logo
#ktor
Title
# ktor
a

Alexandre Brown

12/20/2021, 7:27 PM
Hello, I'm using Ktor 2.0 and getting a weird error when deserializing the response body<T> using kotlinx serialization.
return response.body<MySerializableDataClass>()
does not work I get an error "No transformation found: class io.ktor.utils.io.ByteBufferChannel -> class common.datasources.dtos.SerializablePredictV2ProtocolResponse" Content-Type: application/json But doing
kotlinx.serialization.json.Json.decodeFromString(SerializablePredictV2ProtocolResponse.serializer(), response.bodyAsText())
works. PS: I'm in a unit test environment, mocking the client engine as per documentation. Any help is appreciated, thanks
Copy code
@Serializable
data class TestDataClass(
	val a: String
)
Copy code
MockEngine {
   respond(
      content = Json.encodeToString(TestDataClass("hello")),
      status = HttpStatusCode.OK,
      headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString())
   )
}
Copy code
val httpClient = HttpClient(engine) {
		install(ContentNegotiation) {
			Json
		}
	}
Copy code
val response = <http://httpClient.post|httpClient.post>("<http://localhost:8080/myurl>")

val testResult = response.body<TestDataClass>()
r

Rustam Siniukov

12/20/2021, 8:28 PM
You need to use
Copy code
install(ContentNegotiation) {
  json()
}
instead. Calling just
Json
doesn’t register serializer for
ContentNegotiation
a

Alexandre Brown

12/20/2021, 8:32 PM
@Rustam Siniukov Could you send me the import? Intellij does not seem to find it. I'm I missing a dependency?
r

Rustam Siniukov

12/20/2021, 8:36 PM
do you have dependency on
ktor-serialization-kotlinx-json
?
a

Alexandre Brown

12/20/2021, 8:36 PM
I didnt, adding it now, just saw the migration guide for 2.0 where they mention it. Trying it now
@Rustam Siniukov It works perfectly now, thanks a lot!
👍 1
8 Views