CodeGym /Các khóa học /Kotlin SELF /Tich hop JSON trong Ktor: ContentNegotiation va kotlinx.s...

Tich hop JSON trong Ktor: ContentNegotiation va kotlinx.serialization

Kotlin SELF
Mức độ, Bài học
Có sẵn

1. Gioi thieu

Neu ban moi bat dau lap trinh, bodyAsText() trong co ve ly tuong: request, nhan ve chuoi, in ra console — qua dep. Van de xuat hien dung luc ban muon lam bat ky dieu gi “co ich”: lay truong id, hien title, cong cac con so, kiem tra completed. Luc do chuoi bien thanh “mot cuc ky tu” rat kho thao tac ma khong mac loi.

Hay tuong tuong ban nhan duoc mot goi hang (JSON), nhung ban khong mo ra ma cu co gang doan noi dung dua tren tieng dong khi lac hop. Lam duoc, nhung rat nhanh se dau dau. “Mo hop” — chinh la serialization/deserialization.

Trong the gioi Kotlin, ta da co mot cong cu quen thuoc: kotlinx.serialization, va Ktor co the ket noi voi no qua plugin ContentNegotiation de tu dong hoa viec “mo hop” va “dong goi”.

Mot so do nho ve huong di:

flowchart LR
    A[HttpResponse] --> B["bodyAsText()"]
    B --> C["Json.decodeFromString⟨T⟩() thu cong"]
    A --> D["response.body⟨T⟩()"]
    D --> E[Doi tuong Kotlin]

Nhanh ben trai — “thu cong”, nhanh ben phai — “lam dung chuan qua Ktor”.

Hai cach tiep can JSON trong Ktor

Bay gio co mot diem quan trong: response.body<T>() khong phai phep mau. Day chi la lop tien loi ma Ktor cung cap thong qua plugin. O client Ktor “trong” (chua cai them), Ktor khong bat buoc phai tu hieu JSON.

So sanh hai cach trong cung mot bang — doi khi nao bo de hieu hon khi moi thu nam canh nhau.

Cach tiep can Ta viet gi Ta kiem soat gi Cam giac thuong gap
Thu cong val text = response.bodyAsText() + Json.decodeFromString<T>(text) Tat ca: khi nao doc chuoi, parse bang Json nao “Minh hieu het, nhung code hoi nhieu”
Qua ContentNegotiation val obj: T = response.body() Thiet lap o muc client, ve sau doc theo kieu “O, ngan gon hon nhieu. Gio chi con nho dung thiet lap”

Hom nay ta nham toi phuong an thu hai, nhung van giu phuong an thu nhat trong dau vi doi khi no huu ich cho viec chan doan (vi du: xem response “song” cua server duoi dang text).

Model du lieu: data class va @Serializable

Khi server tra ve JSON, thuong no la mot object co cac thuoc tinh. De bien no thanh Kotlin object, ta can model. Va trong 99% truong hop, do se la data class, vi day la “container du lieu”, khong phai “hanh vi va business logic”.

Ben duoi, kotlinx.serialization hoat dong nhu sau: ban danh dau class bang annotation @Serializable, va compiler se sinh ra code co the doc/ghi JSON cho class do.

Hay lay mot vi du JSON don gian ma nhieu public API dung de demo. Chon han, JSONPlaceholder tra ve TODO dang nhu sau (xap xi):

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Mo ta model (hoan toan “phang”, khong lam phuc tap):

import kotlinx.serialization.Serializable

@Serializable
data class TodoDto(
    val userId: Int,
    val id: Int,
    val title: String,
    val completed: Boolean
)

Luu y: ten truong rat quan trong. Mac dinh, serialization se mapping ten truong Kotlin ↔ key JSON. Neu server gui userId, thi truong cung nen ten userId; neu khong, ban se phai bat them thiet lap hoac dung annotation (vi du @SerialName, nhung day da la chu de serialization nang cao).

2. Cau hinh HttpClient cho JSON

Bay gio ta se lam buoc quan trong nhat cua bai: tao mot client co the lam viec voi JSON “nhu voi kieu du lieu”.

Ve mat ky thuat, ta lam hai viec:

  1. Cai plugin ContentNegotiation
  2. Ben trong no, bat ho tro JSON dua tren kotlinx.serialization

Khung (skeleton) ham factory tao client trong nhu sau:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json

fun buildJsonClient(): HttpClient =
    HttpClient(CIO) {
        install(ContentNegotiation) {
            json(
                Json {
                    ignoreUnknownKeys = true
                }
            )
        }
    }

Thiet lap ignoreUnknownKeys = true gan nhu la “bat buoc” trong thuc te. Tai sao? Vi server rat hay them field moi. Va code hoc tap cua ban khong nen bi vo chi vi API giau hon mot chut. Thiet lap nay noi: “Neu trong JSON co field ma model khong co — cu bo qua”.

Nhac lai — y nghia cua buoc nay la Ktor gio co the:

  • doc body cua response
  • nhan ra day la JSON (dua tren Content-Type trong response)
  • bien JSON thanh object cua kieu can thiet

Mot so tinh tiet huu ich cua Json { ... }

Khi ban viet Json { ... }, co kha nhieu tuy chon. Nguoi moi de muon bat tat ca cung luc, giong nhu dung lo vi song: “cho cong suat 1000W, grill va che do ‘pizza’ dong thoi”. Nhung tot hon la hieu nhung tuy chon thuc dung nhat.

Ta da chon ignoreUnknownKeys = true nhu mot thiet lap “de khong vo vi field du”.

Mot tuy chon khac doi khi huu ich trong project hoc tap:

val json = Json {
    ignoreUnknownKeys = true
    prettyPrint = true
}

prettyPrint anh huong chu yeu toi serialization (khi ban encode object thanh JSON) — JSON se dep hon, co xuong dong. Voi server thuong khong quan trong, nhung voi con nguoi khi xem log thi de chiu hon.

Con isLenient, coerceInputValues, explicitNulls va cac tuy chon khac la nhung “che do tuong thich” tinh vi. O day ta chua dung: khi chua gap van de thi dung lam phuc tap.

3. Doc JSON response thanh object: response.body<T>()

Gio ta ghep mot vi du nho: ta lam GET va doc TodoDto khong phai “bang tay”, ma bang response.body().

Quan trong: de dung response.body<T>(), thuong ban can import io.ktor.client.call.* (hoac import truc tiep body).

Day la vi du toi thieu. Ta co y giu phong cach “don gian”: nhan HttpResponse, sau do doc body. Diem vao — main.

import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val client = buildJsonClient()
    try {
        val response: HttpResponse =
            client.get("https://jsonplaceholder.typicode.com/todos/1")

        val todo: TodoDto = response.body()
        println(todo) // TodoDto(userId=1, id=1, title=..., completed=false)
    } finally {
        client.close()
    }
}

O day dang xay ra gi theo tung buoc:

  1. client.get(...) tra ve HttpResponse (giong nhu truoc).
  2. response.body<TodoDto>() (trong truong hop nay thong qua val todo) yeu cau Ktor: “Hay dua cho toi body duoi dang TodoDto”.
  3. Ktor tim converter phu hop (JSON), parse va tra ve object.

Tai sao response.body() khong can <TodoDto>

Vi Kotlin co the suy ra kieu tu context: ben trai la val todo: TodoDto, nen T chinh la TodoDto. Noi chung, body() la ham generic tra ve gia tri kieu T.

Neu ban muon viet ro kieu hon (doi khi co ich cho nguoi moi), co the lam nhu sau:

import io.ktor.client.call.body
import io.ktor.client.statement.HttpResponse

suspend fun readTodo(response: HttpResponse): TodoDto {
    return response.body<TodoDto>()
}

Cach xem response “song” va khong doc body hai lan

Trong thuc te, ban thuong muon: “neu co gi sai — hay cho toi xem text goc”. Day la thoi quen tot: khi JSON khong parse duoc, de nhat la nhin chuoi goc.

Nhung co mot tinh tiet: body response thuong chi doc duoc mot lan. Vi vay ly tuong nhat ban chon mot trong hai cach: hoac bodyAsText(), hoac body<T>().

Trong phong cach hoc tap (khong di sau vao xu ly loi, vi do la bai tiep theo): ta tao rieng mot ham doc thanh object, con debug de danh cho nhung lan chay rieng.

Vi du, phien ban “text” de debug:

import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText

suspend fun debugPrintBody(response: HttpResponse) {
    val text = response.bodyAsText()
    println(text) // in ra toan bo JSON
}

Va phien ban “chay that”:

import io.ktor.client.call.body
import io.ktor.client.statement.HttpResponse

suspend fun readTodoDto(response: HttpResponse): TodoDto {
    return response.body()
}

Doi khi lap trinh vien lam the nay: in bodyAsText() truoc, sau do moi thu body<T>() — va gap loi rat kho hieu. Day khong phai bi an, chi don gian la “ban da an mat chiec banh quy do, lan hai se khong con nua”.

4. Gui JSON len server: POST va setBody(...)

Truoc do ta “chi doc”. Nhung tich hop JSON se de chiu nhat khi ban gui Kotlin object, va no tu dong bien thanh JSON body cua request.

Lam mot model request don gian. Vi du: “tao task”:

import kotlinx.serialization.Serializable

@Serializable
data class CreateTodoRequest(
    val title: String,
    val completed: Boolean
)

Gio gui POST. O day ta can setBody(...) va quan trong la chi ro Content-Type: application/json (de server hieu dinh dang). Trong Ktor, viec nay lam qua contentType(ContentType.Application.Json).

import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val client = buildJsonClient()
    try {
        val response: HttpResponse =
            client.post("https://jsonplaceholder.typicode.com/todos") {
                contentType(ContentType.Application.Json)
                setBody(CreateTodoRequest(title = "Learn Ktor", completed = false))
            }

        println("status=${response.status.value}") // status=201 (thuong dung cho create)
        println("body=${response.bodyAsText()}")   // body=... (server se tra ve JSON)
    } finally {
        client.close()
    }
}

Nhung dieu quan trong can nhin ra:

  1. setBody(obj) hoat dong theo huong type-safe: ban thuc su truyen vao mot object.
  2. ContentNegotiation + json(...) giup Ktor hieu: “Aha, minh biet serialize CreateTodoRequest thanh JSON”.
  3. contentType(ContentType.Application.Json) la hop dong ve format. Neu khong chi ro, server co the hieu body theo bat ky kieu nao (hoac tu choi).

5. Mini client Todo Console

Gio se co mot doan “thuc hanh” nho: ta lam mini ung dung co the:

  • hoi nguoi dung id cua task
  • goi network
  • in ra title va completed

Khong co layer kien truc va khong xu ly loi nang cao — chi de tu tay cam nhan rang lam viec voi object de chiu hon nhieu so voi lam viec voi chuoi.

Nho lai: Ktor la thu vien de tao cac thu “HTTP-related” trong he sinh thai Kotlin, va no duoc dung nhieu trong thuc te.

Ham nho nhap Int

Lam phien ban don gian nhat: doc chuoi, parse sang Int (ta da biet cach lam).

fun readIntPrompt(prompt: String): Int {
    print(prompt)
    return readln().trim().toInt()
}

Request: lay todo theo id

import io.ktor.client.call.body
import io.ktor.client.request.get

suspend fun fetchTodo(client: io.ktor.client.HttpClient, id: Int): TodoDto {
    val url = "https://jsonplaceholder.typicode.com/todos/$id"
    val response = client.get(url)
    return response.body()
}

Luu y: chu ky ham don gian vi ta chua ban ve loi mang. Nhưng ngay ca nhu vay, y tuong van ro: “lay id → lam GET → nhan TodoDto”.

Main chinh

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val client = buildJsonClient()
    try {
        val id = readIntPrompt("Nhap id cua task: ")
        val todo = fetchTodo(client, id)

        println("title=${todo.title}")           // title=...
        println("completed=${todo.completed}")   // completed=false
    } finally {
        client.close()
    }
}

Va day chinh la hieu ung then chot cua bai hom nay: ban khong “parse JSON”, ban lam viec voi du lieu.

6. Loi thuong gap

Loi so 1: quen cai ContentNegotiation roi thac mac vi sao body<T>() khong hoat dong.
Day la kinh dien: ban viet model, viet response.body<MyDto>(), roi tiep theo hoac la loi, hoac hanh vi ky la. Nguyen nhan gan nhu luon chi co mot: client khong biet cach bien JSON thanh object. Cach sua chi o mot noi — cau hinh HttpClient { install(ContentNegotiation) { json(...) } }.

Loi so 2: model khong khop JSON, nhung ban nghi “Kotlin se tu doan”.
Kotlin thong minh, nhung khong doc y nghi. Neu server gui userId ma ban dat truong la user_id, no se khong tu mapping. Neu server gui chuoi "1" ma ban cho Int, se rat “dau”. O nhung buoc dau, ky luat don gian: ten truong Kotlin = key JSON, va kieu du lieu phai khop. Ve sau moi hoc @SerialName va cac quy tac linh hoat hon.

Loi so 3: doc body hai lan: dau tien bodyAsText(), sau do body<T>().
Giong nhu mo nuoc ep, uong het, roi di than phien voi cai chai rang no rong. Response mang thuong la stream du lieu, chi doc duoc mot lan. Hay chon: hoac text, hoac object. De debug, tot hon la chay rieng mot lan hoac viet rieng ham doc text va in ra.

Loi so 4: gui object qua setBody(...), nhung khong chi ro Content-Type: application/json.
Voi ban, object ro rang la “dang JSON”, nhung voi server do chi la “mot dong byte nao do”. Neu ban khong chi ro Content-Type, server co the cho rang day la form-data, plain text, hoac khong biet la gi. Thoi quen trong Ktor rat don gian: khi POST JSON, luon viet contentType(ContentType.Application.Json) gan setBody(...).

Loi so 5: khong bat ignoreUnknownKeys = true, va project “vo” chi vi co them field.
Day la tinh huong rat thuong: API cap nhat, them field, va client cua ban dot nhien khong parse duoc response. Voi project hoc tap, cam giac se la “hom qua con chay, hom nay hong, minh khong doi gi ca”. Vi vay ignoreUnknownKeys = true gan nhu la cau hinh chuan cho client, nhat la khi ban khong kiem soat server.

1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Đối tượng TODO
Đối tượng TODO
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Mô hình ngắn
Mô hình ngắn
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
TODO theo id
TODO theo id
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Tạo TODO
Tạo TODO
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION