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

Edoardo Luppi

11/01/2021, 10:41 AM
Hi everyone! I'm trying to understand how to receive a JSON response without parsing it a Kotlin object (e.g. I need a pure JSONObject) However all I can find is about serialization and de-serializazion to objects. Any link on documentation that describes how to do what I need?
b

Big Chungus

11/01/2021, 11:04 AM
call.receive<JsonObject>()
e

Edoardo Luppi

11/01/2021, 11:05 AM
@Big Chungus that means I need
Copy code
implementation("io.ktor:ktor-client-serialization:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0")
as dependencies too, right?
b

Big Chungus

11/01/2021, 11:06 AM
Yes, you can do that with other json engines too if you want. E.g. gson or jackson
e

Edoardo Luppi

11/01/2021, 11:07 AM
@Big Chungus thanks! Tho I think the only multiplatform-capable is the kotlinx one
👌 1
b

Big Chungus

11/01/2021, 11:07 AM
You can also get plain json string without those deps via call.receive<String>()
✔️ 1
e

Edoardo Luppi

11/01/2021, 11:09 AM
@Big Chungus and then I can parse them with whatever I want. Although it adds another processing step instead of reading directly from the HTTP output buffer
b

Big Chungus

11/01/2021, 11:09 AM
Yes. For js you could get the string and use native JSON.parse()
You can also receive http output buffer instead of string
✔️ 1
e

Edoardo Luppi

11/01/2021, 11:13 AM
@Big Chungus thanks. Last question regarding JsonElement. It seems the API is pretty simple compared to what other frameworks I'm used to offer (e.g. Unirest, Gson). For example, to get a string value, one has to use
Copy code
json[key]!!.jsonPrimitive.content
instead of a simple
Copy code
json.getString(key)
Are there wrappers for this, or do I have to implement my extension functions?
b

Big Chungus

11/01/2021, 11:16 AM
You can play around with KON which is built on top of simple Map<String, Any?>
kobj(call.receive<KON>()){ // do stuff }
Or even call.receive<JsonObject>().toKobj().apply {}
e

Edoardo Luppi

11/01/2021, 11:23 AM
@Big Chungus thanks, will give it a try!
44 Views