I’ve got an endpoint that returns valid JSON with ...
# ktor
m
I’ve got an endpoint that returns valid JSON with
Content-Type text/html; charset=UTF-8
. The response is as follows
{ "result": [ "foo", "bar" ] }
. When I try to serialize this into a POJO Ktor I get the following error:
No transformation found: class io.ktor.utils.io.ByteBufferChannel -> class FooList
This is most certainly about the wrong
Content-Type
, as with valid
application/json
header everything works as expected. Unfortunately, I cannot change the server’s headers. Is there a workaround for this on client side? I tried with
accept(ContentType.Text.Plain)
as well as
accept(ContentType.Any)
but those don’t really help.
With search I can find some workarounds for this, such as manually serializing the response. I’d like to avoid this, if possible 😄
In case someone stumbles upon this and wonders about the manual decoding:
Json.decodeFromString<FooClass>(response.body())
r
you can register any Content-Type header value with
ContentNegotiation
plugin
Copy code
install(ContentNegotiation) {
  register(ContentType.Text.Plain, KotlinxSerializationConverter(Json))
}
m
Thanks! Which Ktor/ContentNegotiation/Serialization version would this be? I can’t see
Json
as a `SerialFormat`: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serial-format/
Righty, after some Googling I ended up with this block inside content negotiation:
Copy code
val format = Json {
                prettyPrint = true
                encodeDefaults = true
            }

            register(ContentType.Text.Plain, KotlinxSerializationConverter(format))
Yet the issue still persists. I would be surprised if there wasn’t something off with the format here. Do you know if there’s docs available for this?
r
what is the response
Content-Type
header?
m
Unfortunately
Content-Type text/html; charset=UTF-8
r
Then you need
ContentType.Text.Html
🙌 1
m
Well, that indeed did the trick 👍 Thanks for the help, I hope there’s enough keywords in the thread so that others can find this in the future 🙂
👍 1