1. Gioi thieu
Khi ban moi bat dau lam viec voi JSON, ban rat muon tin vao mot cau chuyen co tich don gian: “JSON luon khop voi model cua toi”. Day la mot cau chuyen rat hay, mien la ban tu viet format hoac ban co hop dong (contract) that chat, va khong ai gui cho ban “id”: "10" thay vi 10. Nhung ngay khi format tro thanh “khong co schema”, “version thay doi”, “doi khi thieu truong”, ban se bat dau hoac la tao ra hang chuc truong nullable, hoac la bat loi giai ma, hoac la gia vo nhu day khong phai van de cua ban (spoiler: se thanh van de cua ban).
JsonElement la mot cach tiep can khac: chung ta khong co gang bien dau vao thanh mot Kotlin-model chat che ngay lap tuc. Thay vao do, chung ta truoc het bien JSON thanh mot cai cay. Roi sau do moi quyet dinh can gi tu cai cay nay, va song chung voi no the nao.
Chinh thuc thi JsonElement la mot sealed class dai dien cho mot JSON-element, va no co the la primitive, array hoac object. Dong thoi toString() in lai cai cay thanh JSON hop le. (kotlinlang.org)
2. JSON nhu mot cay: y tuong DOM nhung khong co HTML
Neu ban tung thay DOM trong trinh duyet, y tuong nay se rat quen: tai lieu (hoac du lieu) la mot cay cac nut. Moi nut co mot loai (type), va moi loai co “noi dung ben trong” khac nhau. Object co cac truong theo key, array co cac phan tu theo index, primitive co gia tri.
Can quen voi y nghia nay: trong JSON khong co dam bao rang goc (root) la object. Root co the la array ([ ... ]), so (123), chuoi ("ok"), boolean (true) hoac null. Vi vay phan xa co ban “ep kieu ngay sang JsonObject” giong nhu di ra duong ma khong mang o, vi “troi co ve cung on”. Doi khi dung. Doi khi—ban se uot.
Mot so do nho ve cach chung ta se tu duy:
flowchart TD
A["Van ban JSON (String)"] --> B["Json.parseToJsonElement(...)"]
B --> C["JsonElement (root)"]
C --> D{"Nut nay la loai gi?"}
D -->|JsonObject| E["Truong: key -> JsonElement"]
D -->|JsonArray| F["Phan tu: [JsonElement]"]
D -->|JsonPrimitive| G["Gia tri (dang primitive)"]
D -->|JsonNull| H["Gia tri null ro rang"]
3. Cac loai nut trong cay JsonElement
De di chuyen tu tin tren cay, ban can biet “giong cay”. Trong kotlinx.serialization, cay JSON co mot vai loai chinh.
Theo tai lieu, JsonElement co the la JsonPrimitive, JsonArray hoac JsonObject.
Ngoai ra con co JsonNull — day la mot doi tuong singleton (object), dai dien cho JSON null.
Gom lai thanh bang de dau het hoang mang:
| Loai nut | Vi du trong JSON | Cach hieu | Giong voi |
|---|---|---|---|
|
|
“tu dien/ban do truong” | |
|
|
“danh sach phan tu” | |
|
|
“mot gia tri” | container cho primitive |
|
|
“null nhu mot nut” | doi tuong singleton |
Hay chu y mot cai bay tam ly nho: JsonNull khong phai la viec thieu truong. No chinh la gia tri null xuat hien ro rang trong JSON. Ve su khac nhau nay, chung ta se noi rieng o phan duoi.
4. Parse chuoi thanh cay: Json.parseToJsonElement(...)
Bay gio se co khoanh khac “tu phuc tap thanh chi con mot dong”. De bien van ban JSON thanh cay, chung ta dung:
- Json.parseToJsonElement(string: String): JsonElement
Tai lieu noi ro: ham nay deserialise chuoi JSON thanh bieu dien tuong ung JsonElement va nem SerializationException neu chuoi khong hop le theo JSON.
Vi du toi thieu — ngan gon va trung thuc:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
fun main() {
val text = """{"id": 10, "name": "Alice"}"""
val root: JsonElement = Json.parseToJsonElement(text)
println(root) // {"id":10,"name":"Alice"}
}
Hay de y mot diem quan trong: chung ta khong dung @Serializable va decodeFromString. Chung ta chi don gian dung cay.
Neu ban doc JSON tu ben “ngoai” (file, nhap tu nguoi dung, API ben thu ba), tot nhat hay quen ngay voi try/catch, vi dau vao co the khong phai JSON, ma la “gan giong JSON” (mot the loai nghe thuat rieng).
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
fun tryParseJson(text: String): JsonElement? {
return try {
Json.parseToJsonElement(text)
} catch (e: SerializationException) {
null
}
}
5. Dieu huong co ban tren cay JsonElement
Khi ban di chuyen tren JsonElement, ban lien tuc lam cung mot viec: gia dinh loai nut, kiem tra, roi di tiep. Vi vay rat tien neu co mot ham nho it nhat biet mo ta thu minh dang cam tren tay.
Kiem tra loai nut bang when
when theo loai nut la cai den pin co ban trong khu rung toi:
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun describe(el: JsonElement): String = when (el) {
is JsonObject -> "object(fields=${el.size})"
is JsonArray -> "array(items=${el.size})"
is JsonPrimitive -> "primitive"
is JsonNull -> "null"
}
O day co mot chi tiet nho: JsonNull ve ky thuat la mot JsonPrimitive (trong he phan cap no ke thua primitive), vi vay trong code thuc te ban thuong se phan biet cac truong hop nay can than hon. Nhung de lam ban do khoi dau thi on.
Dieu huong: object → field → array → elements
Gio ta se minh hoa dieu huong “object → field → array → elements”. Lam toi da truc dien, nhung da co ep kieu an toan as?:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun main() {
val root = Json.parseToJsonElement("""{"tags":["kotlin","json"]}""")
val obj = root as? JsonObject ?: return
val tags = obj["tags"] as? JsonArray ?: return
for (tagEl in tags) {
val tag = (tagEl as? JsonPrimitive)?.content
println(tag) // kotlin sau do json
}
}
Day chua phai code “dep”, nhung rat co tinh chat hoc: moi buoc deu chi ro ta co the sai o dau ve type. Trong bai giang tiep theo, ta se bien nhung doan nay thanh cac helper-function gon gang, de khong phai viet lap di lap lai 200 lan (vi thuong thi day la cach burnout bat dau).
Vi sao JsonObject["key"] tra ve JsonElement?
Khi ban lay truong tu JsonObject, ban viet kieu obj["name"]. Va gio phan thu vi bat dau: ket qua la nullable. Day khong phai tro dua, ma la mo hinh the gioi dung.
Ly do don gian: truong co the khong ton tai. Va “khong co truong” khong giong “truong co gia tri null”.
Minh hoa bang vi du. Ta co hai JSON:
1) Hoan toan khong co truong: {}
2) Co truong nhung bang null: {"nickname": null}
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
fun main() {
val obj1 = Json.parseToJsonElement("""{}""") as JsonObject
val obj2 = Json.parseToJsonElement("""{"nickname": null}""") as JsonObject
val a = obj1["nickname"]
val b = obj2["nickname"]
println(a == null) // true (khong co truong)
println(b is JsonNull) // true (co truong, nhung gia tri = null)
}
Su khac nhau nay rat quan trong, vi ve sau (khi validate va “trich xuat an toan”) ban se ra quyet dinh kieu: “neu khong co truong — la loi”, “neu co truong va null — cho phep”, “neu truong la chuoi — ok, neu la array — bao loi”.
Hom nay muc tieu don gian hon: hoc cach nhin thay cac truong hop nay va khong nham lan chung.
Cach doc cay “theo chieu sau” ma khong bien code thanh mot mon hon do
O giai doan nay rat de lam code mat doc. Nguoi moi thuong viet: “noi chuoi ngay, khong dung lai”. Ket qua la thu gi do nhu obj["x"]!!.jsonObject["y"]!!.jsonArray[0]..., va no se sap ngay khi cau truc lech mot chut.
Hom nay ta chua xay dung helper-function ly tuong (se o bai tiep theo), nhung ta co the ap dung style co ban da giup code binh tinh hon: di tung buoc nho va dat ten bien de hieu.
Day la vi du “lay array items tu object” — khong cuong dieu nhung de doc:
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
fun getItemsArray(rootObj: JsonObject): JsonArray? {
val itemsEl = rootObj["items"] ?: return null
return itemsEl as? JsonArray
}
O doan nay nhieu nguoi se hoi: “sao khong dung as JsonArray?” Vi bay gio ta dang lam viec voi cau truc dong. Neu ta nham—hay de no thanh null, khong phai crash. Con phan ung the nao voi null la quyet dinh o tang cao hon (va se xuat hien trong bai ve trich xuat an toan va validate).
6. Root JSON khong bat buoc la object
O cap do thoi quen, rat quan trong la dung suy nghi: “root = object”. Trong the gioi JSON, khong co bat buoc nhu vay. Va neu ban viet code sap ngay khi thay ky tu dau la "[", thi xin chuc mung: parser cua ban song trong the gioi dao duc nghiem khac, con du lieu thi khong.
Hay xem ba kieu root.
Root la array
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
fun main() {
val root = Json.parseToJsonElement("""[1, 2, 3]""")
val arr = root as? JsonArray ?: return
println(arr.size) // 3
}
Root la primitive
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
fun main() {
val root = Json.parseToJsonElement("42")
val p = root as? JsonPrimitive ?: return
println(p.content) // 42
}
Root la null
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNull
fun main() {
val root = Json.parseToJsonElement("null")
println(root is JsonNull) // true
}
Vang, JSON co the chi la null. Doi khi day con la “contract hop le” (du nghe nhu meme).
7. Mini inspector JSON cho ung dung console
De khong de kien thuc tro nen “trong chan khong”, hay them vao ung dung console hoc tap cua ta mot tinh nang debug nho. Nho lai mach truyen cua khoa hoc: ta da tung luu du lieu trong JSON, nhung luc do format on dinh va ta decode vao model. Bay gio ta them che do nhan van ban JSON va noi: “cau truc cua thu nay la gi?”.
Day khong phai “xu ly day du”, ma la inspector. No se huu ich khi file/input khong dung nhu ky vong, va ban muon nhanh chong hieu cho nao thuc tai bi vo.
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun inspectJson(text: String): String {
val root: JsonElement = try {
Json.parseToJsonElement(text)
} catch (e: SerializationException) {
return "Day khong phai JSON"
}
return when (root) {
is JsonObject -> "Root: object, so truong=${root.size}"
is JsonArray -> "Root: array, so phan tu=${root.size}"
is JsonPrimitive -> "Root: primitive (${root.content})"
is JsonNull -> "Root: null"
}
}
Va mot main nho xiu de thay chay thuc te:
fun main() {
val text = readln()
println(inspectJson(text))
// Vi du input: {"id":1,"name":"Ann"}
// Output: Root: object, so truong=2
}
Vang, trong rat don gian. Nhung chinh nhung “thu don gian” nay ve sau se tiet kiem hang gio debug: it nhat ban hieu minh dang parse cai gi, va vi sao code mong doi object lai nhan duoc array.
8. Loi thuong gap khi lam quen voi JsonElement
Loi #1: nghi rang root JSON luon la object.
Day la cai bay gap nhieu nhat, vi phan lon cac vi du JSON “dep” tren internet deu bat dau bang {...}. Trong thuc te, root co the la array, primitive hoac null, va JsonElement ton tai chinh la de ban khong phai dua tren gia dinh sai. Hay kiem tra type cua root ro rang, dac biet o noi JSON den tu ben ngoai.
Loi #2: ep kieu bat buoc as JsonObject ma khong kiem tra.
Ep kieu bat buoc la cuoc dat cuoc “toi chac 100%”. Voi JSON khong on dinh, gan nhu luc nao cung la dat cuoc chong lai chinh minh. An toan hon la bat dau bang as? va thoat som (return), trong khi ban dang hieu cau truc. Roi khi ban them lop validate, ban moi dua ra cac quyet dinh nghiem ngat hon.
Loi #3: nham lan giua thieu truong va gia tri null cua truong.
obj["key"] tra ve null neu khong co truong, con neu truong co ton tai va bang JSON null, ban se nhan duoc JsonNull. Hai truong hop nay thuong co y nghia khac nhau trong business-logic: “khong gui” va “gui nhung rong” khong giong nhau.
Loi #4: nghi rang parseToJsonElement “an toan va khong bao gio crash”.
Parse se that bai voi JSON khong hop le va nem SerializationException. Dieu nay binh thuong, trung thuc, va can duoc xu ly. Dac biet neu ban cho nguoi dung nhap JSON bang tay (con nguoi biet go phim, nhung doi khi se them mot dau phay thua vi qua yeu nghe thuat).
Loi #5: co gang “lam moi thu” trong mot ham duy nhat.
Nguoi moi thuong tron parse, dieu huong, trich xuat, default, kiem tra range va in loi trong mot khoi khong lo. Ket qua la code khong the bao tri. Hom nay chung ta co y gioi han o bac dau tien: nhin JSON nhu mot cay va hoc dieu huong co ban. Sau do se la trich xuat an toan va mot lop validate rieng—va chinh o do se xuat hien kien truc gon gang.
GO TO FULL VERSION