1. Gioi thieu
Khi ban lan dau lam quen voi kotlinx.serialization, co the ban se co cam giac: “Tuyet! Bay gio bat ky JSON nao minh cung bien thanh data class duoc, va the la cuoc doi de tho”. Trong thuc te, cuoc doi nhu thuong le van phuc tap hon mot chut: doi khi dinh dang bao cao khong trung voi cac model cua ban, doi khi can tra ve chi mot phan truong, doi khi — can them cac gia tri tong hop ma trong model hoan toan khong co. Va chinh luc do, lap rap JSON thu cong se bien tu “ui, do che” thanh “a, dung la cong cu tien”.
Hay tuong tuong du an console thuc hanh cua chung ta (mot ung dung theo doi chi tieu gia dinh): ben trong chuong trinh ta co cac cau truc Kotlin binh thuong (Expense, list, map), va ta muon lam “xuat bao cao” ra JSON de tich hop voi bat ky thu gi. Nhung bao cao — khong phai chi la mot Expense, ma la mot cau truc kieu:
- tong so tien,
- tong theo danh muc,
- danh sach giao dich,
- muc he thong meta (phien ban dinh dang, tien te, tac gia bao cao).
Neu thu “chi serialize list chi tieu”, ta se mat cac gia tri tong hop. Neu thu “lam mot data class Report khong lo”, no se phong to dan, trong khi dinh dang bao cao lai tu phat trien theo cach rieng va keo theo viec lam vo model domain cua ban. Vi vay hom nay ta hoc cach xay JSON nhu dung bo lap rap: gon gang, du doan duoc, va khong noi chuoi (noi chuoi la con duong dan toi vuong quoc cua dau phay bi quen).
2. Mo hinh tu duy: bao cao JSON nhu mot pipeline
Truoc khi viet code, nen “thoa thuan” voi nao rang o day co hai the gioi khac nhau: “tinh toan” va “dong goi vao JSON”. Neu tron chung vao mot ham khong lo, se thanh mon sup: khong ngon, va debug thi phai dung ca muoi. Vi vay hay giu pipeline don gian: dau tien tinh toan trong Kotlin, sau do dong goi vao cay JSON.
Day la so do ma ta se lap di lap lai nhu mot cau than chu (va dung, lap trinh vien cung thich than chu, chi la ho goi no la “pattern”):
flowchart TD
A[Du lieu trong Kotlin: List⟨Expense⟩] --> B[Tinh toan: total, byCategory]
B --> C[Lap rap JsonElement: buildJsonObject/buildJsonArray]
C --> D[Ma hoa thanh chuoi: Json.encodeToString]
D --> E[Xuat/luu]
Tu goc nhin Kotlin, buildJsonObject { ... } va buildJsonArray { ... } la cac DSL builder dua tren lambda co receiver: trong block, ban nhu “dang o ben trong” doi tuong builder va goi method cua no. Duoi mui, compiler co gang suy luan type de ban viet it “tu thua” hon — cung tinh than voi apply/with va cac cau truc “idiomatic” khac. Neu dao sau hon nua, cac builder-DSL kieu nay trong Kotlin gan voi co che suy luan type ben trong lambda (builder-style inference).
3. Chuan bi: JsonElement, model va bo chuyen doi
Cac vien gach co ban cho viec lap rap JSON thu cong
De lap rap JSON thu cong, dieu quan trong la dung nghi “minh dang viet JSON”, va bat dau nghi “minh dang tao JsonElement”. Cach nghi nay giam manh nguy co mac loi cu phap, vi loi se tro thanh “loi kieu type” (compiler bao), chu khong phai “loi kieu chuoi” (nguoi dung bao).
Duoi day — bo toi thieu hom nay ta can:
| Muon nhan duoc gi | Dai dien bang gi |
|---|---|
JSON object |
→ |
JSON array |
→ |
| Chuoi/so/boolean | |
|
|
Bat dau voi vi du cuc ngan de cam nhan cu phap va khong bi “ngop”. O day khong co logic domain, chi “lap object → in ra”.
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
fun main() {
val obj: JsonObject = buildJsonObject {
put("status", JsonPrimitive("ok"))
put("count", JsonPrimitive(3))
put("note", JsonNull)
}
println(obj) // {"status":"ok","count":3,"note":null}
}
Luu y: put nhan vao JsonElement, vi vay cac gia tri “tho” nhu Int va String can duoc chuyen thanh JsonPrimitive. Dung, hoi dai dong hon mot chut — nhung doi lai rat ro rang.
Model du an: Expense va du lieu cho bao cao
De vi du khong bi “treo trong chan khong”, ta tiep tuc theo dong du an thuc hanh. Gia su ta co mot khoan chi: id, ten, danh muc va so tien (tinh theo don vi tien te nguyen, de khong phai tranh luan ve phan thap phan va lam tron).
Neu trong du an cua ban ten truong hoi khac mot chut — khong sao: hom nay quan trong la phong cach, khong phai ten cu the.
data class Expense(
val id: Int,
val title: String,
val category: String,
val amount: Int
)
Gio ta phac thao mot danh sach chi tieu nho de bao cao co the duoc lap rap truc tiep trong main. Trong du an that, danh sach se den tu kho luu tru cua ban (file/bo nho), nhung luc nay dieu quan trong hon la “lap rap JSON nhu the nao”.
fun sampleExpenses(): List<Expense> = listOf(
Expense(id = 1, title = "Ca phe", category = "Do an", amount = 220),
Expense(id = 2, title = "Di lai", category = "Giao thong", amount = 75),
Expense(id = 3, title = "Pizza", category = "Do an", amount = 540)
)
JSON cho mot thuc the: expenseToJson(...)
Khi ban xay bao cao, gan nhu luc nao cung co phan lap lai: “mot phan tu trong JSON trong nhu the nao”. Neu khong tach ra thanh ham, code se bi lan ra voi hang dong put("id", JsonPrimitive(...)) — va sau do the nao ban cung se cap nhat dinh dang o mot noi, nhung quen o noi khac. Day la loi co dien “minh co hai phien ban su that”, khong triet hoc gi nhung day bug.
Ta lam mot converter nho chuyen mot khoan chi thanh JsonObject. No khong “serialize mot cach ma thuat”, ma ro rang tach tung truong — va do la diem cong, vi ban kiem soat 100% dinh dang.
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
fun expenseToJson(e: Expense): JsonObject = buildJsonObject {
put("id", JsonPrimitive(e.id))
put("title", JsonPrimitive(e.title))
put("category", JsonPrimitive(e.category))
put("amount", JsonPrimitive(e.amount))
}
Tu day, bao cao se duoc lap rap nhu LEGO: bien list chi tieu thanh mang cac JSON object qua expenseToJson, thay vi viet lai tung truong moi lan.
4. Lap rap bao cao: tong hop va mang phan tu
Gio den phan hay nhat: bao cao thuong chua “tat ca trong mot”. Va dieu do khong co gi dang so neu ban khong co tinh toan tong tien ngay ben trong buildJsonObject. Ta se lam cho “dung cach”: tinh truoc, dong goi sau.
Tinh cac gia tri tong hop trong Kotlin
Dau tien la tong tien:
fun totalAmount(items: List<Expense>): Int =
items.sumOf { it.amount }
Sau do la tong theo danh muc. Dung, co nhieu cach lam; ta chon cach don gian va de doc: group truoc, sau do sum tung group.
fun totalByCategory(items: List<Expense>): Map<String, Int> =
items.groupBy { it.category }
.mapValues { (_, list) -> list.sumOf { it.amount } }
Dong goi cac gia tri tong hop vao JSON
Gio ta lap rap JsonObject tong. Ben trong se co total, object byCategory va array items.
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
fun buildExpensesReport(items: List<Expense>): JsonObject {
val total = totalAmount(items)
val byCat = totalByCategory(items)
return buildJsonObject {
put("total", JsonPrimitive(total))
put("byCategory", buildJsonObject {
for ((category, amount) in byCat) {
put(category, JsonPrimitive(amount))
}
})
put("items", buildJsonArray {
for (e in items) add(expenseToJson(e))
})
}
}
O day can cam nhan ro: byCategory la mot JSON object long nhau, con items la mot JSON array long nhau. Ta khong “in JSON”, ta dang xay dung cay phan tu.
5. Cau truc bao cao khong tieu chuan
Bao cao hiem khi la “ban sao cua database”. Thuong dinh dang can nhung dieu ky la: doi ten key, gop truong, section co dieu kien, hoac long nhau ma model khong co. Lap rap thu cong chinh la de phuc vu viec do: ban mo ta dinh dang truc tiep trong code ma khong phai co gang ep no vao model domain.
Doi ten key va cac truong “than thien voi nguoi”
Gia su ta muon trong bao cao khong dung title, ma dung name, va them truong amountText (dang chuoi), vi nhu vay tien hien thi UI hon (dung, co the tranh cai, nhung bao cao doi khi van lam the).
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
fun expenseToPublicJson(e: Expense): JsonObject = buildJsonObject {
put("id", JsonPrimitive(e.id))
put("name", JsonPrimitive(e.title))
put("amount", JsonPrimitive(e.amount))
put("amountText", JsonPrimitive("${e.amount} ₣ "))
}
Hay de y: model domain khong doi, nhung dinh dang bao cao thi doi. Day la dau hieu tot: ban khong “pha” business logic chi de phuc vu xuat du lieu.
JsonNull vs khong co truong
Mot tinh huong rat hay gap: “truong khong ton tai” va “truong ton tai nhung null” — khong giong nhau. Ke ca ban thay nhu giong, o dau do o dau ben kia day co mot nguoi (hoac service) se nghi khac. Vi vay ta can lam duoc ca hai kieu.
Mo phong truong comment: doi khi co, doi khi khong.
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
fun expenseWithCommentJson(e: Expense, comment: String?): JsonObject = buildJsonObject {
put("id", JsonPrimitive(e.id))
put("title", JsonPrimitive(e.title))
if (comment == null) {
put("comment", JsonNull) // truong ton tai, nhung no la null
} else {
put("comment", JsonPrimitive(comment))
}
}
Gio la phien ban “neu khong co comment — thi khong co key luon”. Day la mot contract khac.
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
fun expenseWithOptionalCommentJson(e: Expense, comment: String?): JsonObject = buildJsonObject {
put("id", JsonPrimitive(e.id))
put("title", JsonPrimitive(e.title))
if (comment != null) {
put("comment", JsonPrimitive(comment)) // khong co truong neu comment == null
}
}
Tu ben ngoai, cac JSON nay trong gan nhu giong nhau, nhung y nghia khac. Va nhung khac biet kieu nay la mot trong cac ly do vi sao lap rap thu cong doi khi “that” hon so voi “tu dong serialize ra sao thi ra”.
6. Cach tiep can lai: mot phan thu cong, mot phan qua encodeToJsonElement(...)
Doi khi ban muon lap rap “vo bao” bao cao thu cong, nhung mot section ben trong thi serialize nguyen trang, vi o do da duoc mo ta dep bang @Serializable. Day la chien luoc binh thuong: ban khong bat buoc phai chon giua “chi thu cong” va “chi data class”.
Ta tao mot phan meta nho cho bao cao (phien ban dinh dang va tien te). No don gian va on dinh — rat hop lam ung vien cho @Serializable.
import kotlinx.serialization.Serializable
@Serializable
data class ReportMeta(
val formatVersion: Int,
val currency: String
)
Gio ta dong goi meta bang Json.encodeToJsonElement(...), con phan con lai — thu cong.
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.encodeToJsonElement
fun buildReportWithMeta(items: List<Expense>): JsonObject {
val meta = ReportMeta(formatVersion = 1, currency = "RUB")
val total = totalAmount(items)
return buildJsonObject {
put("meta", Json.encodeToJsonElement(meta))
put("total", JsonPrimitive(total))
}
}
Vi sao tien? Vi ReportMeta la “mot model du lieu nho”, co the tai su dung. Con bao cao thi la “cau truc khong tieu chuan”, nen de kiem soat thu cong se thoai mai hon.
7. Cach bien JsonElement thanh chuoi
Khi ban da lap rap JsonObject hoac JsonArray, se co mot cau hoi don gian: “OK, the lam sao lay ra van ban JSON dung nghia?”. Trong Kotlin ban se muon goi .toString() — va dung, no se cho ra bieu dien JSON. Nhung gan nhu luon la mot chuoi gon tren mot dong. Cho log thi on, nhung cho bao cao de con nguoi doc thi thuong can “dep”.
Lam hai phien ban: compact va pretty.
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.serializer
fun main() {
val report: JsonObject = buildJsonObject { put("status", JsonPrimitive("ok")) }
println(report.toString()) // {"status":"ok"}
val prettyJson = Json { prettyPrint = true }
val text: String = prettyJson.encodeToString(JsonElement.serializer(), report)
println(text) // JSON nhieu dong dep de doc
}
Diem quan trong: ta ma hoa chinh JsonElement, vi bao cao cua ta da la cay JSON, khong phai class @Serializable. Rat hop ly: hom nay ta xay JSON “nhu mot cau truc”, chu khong phai “nhu mot model”.
8. Loi thuong gap khi lap rap JSON thu cong
Loi so 1: noi chuoi de tao JSON.
Khi tay ban muon viet "{\"total\": $total}", hay nho rang ban da biet xay JsonObject. Noi chuoi se vo tran truoc dau ngoac kep, xuong dong, escape, va “o day can dau phay khong?”. Voi buildJsonObject, it nhat compiler la dong minh, khong phai ke dung ngoai lanh lung.
Loi so 2: tron tinh toan bao cao va dong goi JSON vao mot cho.
Neu ben trong buildJsonObject { ... } ban bat dau lam groupBy, sumOf, sort, filter, code se nhanh chong thanh “may gap lien hop”. Hay tinh het vao bien Kotlin truoc (val total, val byCat), roi moi tu tu dong goi. Cach nay giup debug ca phan tinh toan lan dinh dang de hon.
Loi so 3: nham lan giua “khong co truong” va “truong = null”.
Neu luc thi bo key, luc thi dat JsonNull, ben tieu thu du lieu ben ngoai co the se hanh xu khac nhau. Day khong phai “tieu tiet”, ma la mot phan contract cua dinh dang. Hay quyet dinh quy tac mot lan va tuan thu o moi noi.
Loi so 4: lap lai ten key bang chuoi trong ca du an.
Hom nay ban viet "total", ngay mai — "Total", ngay kia — "sum", va the la bao cao “doi khi doc duoc”. Ke ca trong du an hoc tap nho, tot hon la dat key o mot noi (vi du, object ReportKeys { const val TOTAL = "total" }) va dung hang so de tranh loi go sai.
Loi so 5: tao “gan nhu JSON” bang cach put vao object thu khong phai JsonElement.
Doi khi nguoi moi thu viet put("count", 3) va ngac nhien vi compiler bao loi. Trong lap rap thu cong, ban lam viec o muc JsonElement, nen so va chuoi can duoc chuyen thanh JsonPrimitive. Dung, dai hon vai ky tu, nhung doi lai dinh dang duoc type-hoa nghiem ngat o muc API.
Loi so 6: co gang lam bao cao “dinh dang universal hoan hao” ngay tu dau.
Bao cao la mot contract. Hom nay ban can total va items, ngay mai — them byCategory, ngay kia — meta. Lap rap thu cong tot o cho ban co the doi dinh dang theo tung diem, nhung khong co nghia la nen nhong vao do moi thu “phong khi can”. Chi lam nhung gi that su duoc dung, va mo rong dan khi can.
GO TO FULL VERSION