CodeGym /Các khóa học /Kotlin SELF /Serialization cho enum va sealed class: discriminator va ...

Serialization cho enum va sealed class: discriminator va Ok/Error

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

1. enum: gia tri trong JSON va @SerialName

Khi ban viet chuong trinh, ban lien tuc can bieu dien “mot trong vai lua chon”. Vi du: trang thai cua mot thao tac (thanh cong/that bai), danh muc chi tieu (an uong/di chuyen), loai lenh ("add"/"list"/"remove") hoac trang thai don hang. Cach ngay tho la luu chung bang chuoi nhu "ok" hoac "food". No chay on cho den khi ban go sai ("foood"), va chuong trinh vui ve tiep tuc hoat dong, nhung da o “vu tru song song”.

enum va sealed class la cach noi voi compiler: “nhin nay, so phuong an it thoi, va khong the co phuong an khac”. Trong Kotlin, dieu nay con de chiu hon nua vi when voi enum va sealed class co the la exhaustive: neu ban quen xu ly mot truong hop, compiler (o che do expression) se phan nan va cuu ban khoi bug. Chinh hanh vi “tap phuong an huu han” nay cung nen duoc giu trong hop dong JSON.

enum mac dinh trong JSON trong nhu the nao

enum ve co ban la “tu dien cac gia tri hop le”. Trong Kotlin, enum class con cho ban nhieu thu tien nhu name, ordinal, entries, valueOf(...), v.v. Nhung hom nay chung ta quan tam dieu chinh: enum duoc chuyen thanh JSON ra sao.

Mac dinh, kotlinx.serialization serialize enum thanh mot chuoi la ten hang so. Tức la FOOD se thanh "FOOD". Cach nay don gian, de doc, va thuong la du. Nhưng co mot van de nho: ten hang so la ten trong code, con JSON la dinh dang ben ngoai. Doi khi dinh dang ben ngoai yeu cau gia tri khac (vi du, "food" thay vi "FOOD"), va doi khi ban muon doi ten hang so trong code ma khong lam hu cac file cu.

Hay lam mot vi du nho dua tren ung dung console hoc tap “quan ly chi tieu”. Mot model chi tieu va category la enum.

import kotlinx.serialization.Serializable

@Serializable
enum class ExpenseCategory {
    FOOD, TRANSPORT, ENTERTAINMENT
}

Gio thu serialize:

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val json = Json { prettyPrint = true }

    println(json.encodeToString(ExpenseCategory.FOOD))
    // "FOOD"
}

Y chinh: trong JSON la ten enum-constant. Va neu ngay mai ban doi ten ENTERTAINMENT thanh FUN (vi muon ngan hon), thi cac JSON cu voi "ENTERTAINMENT" se khong doc duoc nhu truoc.

Gia tri on dinh voi @SerialName

Luc nay thuong xuat hien mot mong muon rat “nguoi”: “the thi dung bao gio doi ten enum”. No giong nhu loi hua “toi se khong bao gio an do ngot”. Ve mat ly thuyet thi duoc, ve mat tam ly thi... kho.

Tot hon la tach “ten noi bo trong code” khoi “ten ben ngoai trong dinh dang”. De lam dieu do, ban co the gan @SerialName cho cac gia tri enum. Khi do ban dat ten hang so trong code sao cung duoc, con trong JSON thi luu dung gia tri da thong nhat theo format.

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
enum class ExpenseCategory {
    @SerialName("food")
    FOOD,

    @SerialName("transport")
    TRANSPORT,

    @SerialName("entertainment")
    ENTERTAINMENT
}

Kiem tra serialize:

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val json = Json { prettyPrint = false }

    println(json.encodeToString(ExpenseCategory.TRANSPORT))
    // "transport"
}

Gio JSON “than thien hon” (hoac “API-hon”) va quan trong hon la on dinh: ban co the doi ten ENTERTAINMENT thanh FUN trong Kotlin, nhung giu @SerialName("entertainment"), va format se khong bi anh huong.

2. sealed class: discriminator va @SerialName

Vi sao JSON can discriminator

Neu enum la “mot trong N gia tri”, thi sealed class la “mot trong N kieu (type)”. Va moi kieu co the mang du lieu rieng. No giong nhu hop bat ngo, nhung “trung thuc”: so bat ngo it, tat ca deu biet truoc, va compiler giu chung trong danh sach.

Vi du kinh dien: ket qua thao tac. Thanh cong mang du lieu huu ich (vi du id cua chi tieu moi tao), con loi mang thong diep loi.

import kotlinx.serialization.Serializable

@Serializable
sealed class OpResult {
    @Serializable
    data class Ok(val id: Int) : OpResult()

    @Serializable
    data class Error(val message: String) : OpResult()
}

Va gio co cau hoi: luu cai nay trong JSON the nao?

Neu chi ghi cac field, ta se mat dieu quan trong nhat: khi doc JSON nguoc lai, lam sao biet day la Ok hay Error? JSON khong co kha niem “sealed class variant”. No chi thay mot object { ... }.

Vi vay, serialization da hinh (va sealed chinh la da hinh “nho gon”) can mot field phu tro dac biet: discriminator kieu. Field nay noi: “variant la loai nay”.

Dang thuong gap:

{ "type": "ok", "id": 10 }

hoac

{ "type": "error", "message": "Invalid input" }

Sau do khi doc JSON, thu vien nhin vao "type" va quyet dinh tao subtype nao.

classDiscriminator trong Json { ... }

Quan trong la discriminator phai co ten on dinh va khong xung dot voi cac field binh thuong. Lua chon pho bien nhat la "type", nhung trong mot so domain, tu type da bi dung cho nghia nghiep vu (“loai hang”, “loai thao tac”). Khi do nen chon ten khac, vi du "kind" hoac "resultType".

Trong kotlinx.serialization, ten field discriminator duoc dat bang cau hinh classDiscriminator.

import kotlinx.serialization.json.Json

val json = Json {
    prettyPrint = true
    classDiscriminator = "type"
}

Mot chi tiet thuc te: cau hinh nay phai giong nhau o noi ban ghi JSON va noi ban doc JSON. Neu ban luu file voi "type", roi sau do doc bang Json { classDiscriminator = "kind" }, thu vien se nhin sai cho va “khong nhan ra” cac variant.

@SerialName tren cac variant: co dinh ok/error

Hien tai variant co ten Ok va Error. Neu serialize “nguyen ban”, format ben ngoai co the phu thuoc vao ten class va package (ma ban hoan toan co the refactor). Ngoai ra, trong JSON thuong muon marker ngan gon, de hieu: "ok" va "error".

O day @SerialName lai giup, nhung lan nay ta gan no khong phai cho field hay enum-value, ma cho subtype cua sealed class.

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
sealed class OpResult {

    @Serializable
    @SerialName("ok")
    data class Ok(val id: Int) : OpResult()

    @Serializable
    @SerialName("error")
    data class Error(val message: String) : OpResult()
}

Gio ta da co dinh ro rang convention Ok/Error nhu mot phan cua hop dong format, thay vi “dat ten class tinh co”.

Kiem tra serialize:

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val json = Json {
        prettyPrint = true
        classDiscriminator = "type"
    }

    val r: OpResult = OpResult.Ok(id = 10)
    println(json.encodeToString(r))
    /*
    {
        "type": "ok",
        "id": 10
    }
    */
}

Hay chu y mot dieu nho nhung quan trong: bien r co kieu OpResult, khong phai OpResult.Ok. Va dieu nay khong chi “dep”, no con anh huong den JSON.

Tinh tiet: discriminator chi xuat hien khi serialize qua kieu co so

Day la luc hoc vien hay gap nhat: “sao no khong chay?” va “sao JSON lai khac?”. Nguyen nhan la kieu tinh (static type) cua bieu thuc trong Kotlin.

Neu ban serialize object nhu kieu cu the OpResult.Ok, thu vien coi “kieu da biet roi”, va discriminator co the khong can. Con neu ban serialize nhu OpResult, thi can discriminator vi co nhieu variant.

So sanh:

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val json = Json { classDiscriminator = "type" }

    val asChild = OpResult.Ok(id = 10)
    val asBase: OpResult = OpResult.Ok(id = 10)

    println(json.encodeToString(asChild)) // {"id":10}
    println(json.encodeToString(asBase))  // {"type":"ok","id":10}
}

Ve mat ky thuat, ca hai JSON deu hop le, nhung cai thu hai co the khoi phuc mot cach ro rang vi no co "type". Cai thu nhat khong the khoi phuc thanh OpResult neu khong co thong tin bo sung: { "id": 10 } co the la bat cu thu gi (va dac biet, co the tro thanh bat cu thu gi sau khi model mo rong).

Quy tac thuc hanh: neu ban thiet ke format JSON cho sealed class va muon decodeFromString<OpResult>(...) on dinh, hay serialize ket qua thong qua kieu co so (hoac chi ro type-parameter).

3. Decode va xu ly bang when

Gio ta lam thao tac nguoc lai: tu JSON ve Kotlin-object. O day ban se cam nhan duoc vi sao can discriminator: chinh no giup thu vien chon dung variant.

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

fun main() {
    val json = Json { classDiscriminator = "type" }

    val s1 = """{"type":"ok","id":10}"""
    val s2 = """{"type":"error","message":"Bad input"}"""

    val r1 = json.decodeFromString<OpResult>(s1)
    val r2 = json.decodeFromString<OpResult>(s2)

    println(r1) // Ok(id=10)
    println(r2) // Error(message=Bad input)
}

Tiep theo la “co dien” Kotlin: xu ly ket qua bang when exhaustive. Tren sealed class dieu nay rat “phe” vi Kotlin biet tat ca variant va co the bat ban xu ly het.

fun toHumanText(r: OpResult): String = when (r) {
    is OpResult.Ok -> "Thanh cong: da tao id=${r.id}"
    is OpResult.Error -> "Loi: ${r.message}"
}

when nay hay o cho: ban khong dung null, khong dung co Boolean kieu isOk, va khong lam “chuoi ma thuat”. Ban co mot model ket qua chat che, va compiler giup ban khong quen xu ly variant.

4. So do nho encode/decode cho sealed

De de hinh dung “vi sao type xuat hien”, hay nhin qua trinh tu nhu mot day chuyen nho.

flowchart TD
    A["Kotlin: OpResult (sealed)"] -->|encodeToString| B["JSON object"]
    B --> C["discriminator field: type"]
    C --> D["value: ok / error"]
    B -->|decodeFromString⟨OpResult⟩| E["Kotlin: OpResult.Ok hoac OpResult.Error"]
    E -->|when| F["van ban de doc / logic tiep theo"]

Neu o buoc JSON ban khong co type, thi duong “di nguoc lai” ve OpResult se hoac la bat kha thi, hoac tro thanh doan mo noi dung object (thuong rat de vo).

5. Vi du trong quan ly chi tieu: ket qua lenh la Ok/Error

Gio ta lam mot buoc co ve nho, nhung tren thuc te giup chuong trinh “truong thanh” hon: dung tra ve “chuoi loi” va bat dau tra ve ket qua chat che Ok/Error. Sau do (neu muon) ta co the serialize ket qua nay sang JSON — vi du de ghi log, de export, de test.

Them cac model toi thieu cua ung dung:

import kotlinx.serialization.Serializable

@Serializable
data class Expense(
    val id: Int,
    val title: String,
    val amount: Int,
    val category: ExpenseCategory
)

Va service them chi tieu va tra ve OpResult. O day co logic don gian, co y “khong co lop kien truc” trong tuong lai — ta van dang hoc cach giu code de hieu.

class ExpenseService {
    private val items = mutableListOf<Expense>()
    private var nextId = 1

    fun add(title: String, amount: Int, category: ExpenseCategory): OpResult {
        if (title.isBlank()) return OpResult.Error("Ten khong duoc de trong")
        if (amount <= 0) return OpResult.Error("So tien phai > 0")

        val e = Expense(id = nextId++, title = title, amount = amount, category = category)
        items.add(e)
        return OpResult.Ok(id = e.id)
    }
}

Hay de y, doc rat “muot”: ham khong tra ve Boolean, khong tra ve Int kieu “-1 la loi”, va khong tra ve String? (noi null la thanh cong, con chuoi la loi). No tra ve mot ket qua mien (domain) ro rang.

Bay gio trong main ta co the demo va tien the hien serialize ket qua:

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val service = ExpenseService()

    val json = Json {
        prettyPrint = true
        classDiscriminator = "type"
    }

    val r: OpResult = service.add("Ca phe", 250, ExpenseCategory.FOOD)
    println(toHumanText(r))                  // Thanh cong: da tao id=1
    println(json.encodeToString(r))
}

Neu ban hoi: “tai sao can serialize OpResult neu toi chi in ra?”, cau tra loi la: hom nay la vi du hoc tap, con thuc te thi cac ket qua nhu vay thuong di vao file (log), di qua mang (API), hoac vao “golden files” cho test. Khi do, ky luat Ok/Error va ten variant on dinh se thuc su “co loi”.

6. Loi thuong gap khi serialize enum va sealed class

Loi so 1: luu enum trong JSON bang ten hang so, roi sau do tu do doi ten no trong code.
Van de khong phai la “khong duoc doi ten”, ma la ban da am tham doi format ben ngoai. Hom nay ban co "FOOD", ngay mai thanh "MEAL", va cac file cu tro thanh bao tang loi. Cach chua don gian: co dinh gia tri ben ngoai bang @SerialName tren cac enum-value, va doi ten Kotlin-name bao nhieu tuy thich (trong gioi han hop ly).

Loi so 2: mong cho sealed class co the khoi phuc tu JSON ma khong can field kieu.
JSON tu than khong luu “thong tin ve subtype”. Neu ban khong them discriminator, thi decodeFromString<OpResult>(...) se khong biet tao subtype nao. Discriminator khong phai “thu tuc thua”, ma la cai gia toi thieu de dam bao tinh don nghia.

Loi so 3: chon ten discriminator trung voi field nghiep vu.
Neu ban dat classDiscriminator = "type", roi sau do trong model lai them field val type: String theo nghia nghiep vu, ban se gap xung dot. Tot nhat hay dat truoc mot ten “du tru” cho discriminator (vi du "type" hoac "kind") va khong dung no trong du lieu binh thuong, hoac chon ten it de trung hon.

Loi so 4: serialize variant sealed nhu mot subtype cu the roi ngam nhien vi discriminator khong xuat hien.
Neu ban serialize OpResult.Ok(...) nhu OpResult.Ok, JSON co the khong co "type". Sau do ban thu doc no nhu OpResult — va the la “toang”. Neu ban thiet ke format ben ngoai, hay serialize qua kieu co so (hoac chi ro kieu bang tham so encodeToString<OpResult>(...)), de discriminator luon co mat.

Loi so 5: tao “vuon thu” variant ket qua thay vi giu cap on dinh Ok/Error.
Rat de muon co Success/Failure, roi o cho khac lai Ok/Error, roi nua la Fine/Bad. Cuoi cung code va format bi phinh to ra, khong thong nhat. Voi du an hoc tap va phan lon thao tac ung dung, nen giu mot mau ket qua duy nhat: Ok cho thanh cong va Error cho that bai. Dieu nay giup xu ly when dong nhat o moi noi va giam so “truong hop dac biet” trong dau.

1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Chi tiêu với danh mục
Chi tiêu với danh mục
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Kết quả thao tác
Kết quả thao tác
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Thông báo kết quả
Thông báo kết quả
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION