Skip to Content
Kotlin📘 Ngôn ngữ KotlinLàm việc với JSON

Làm việc với JSON trong Kotlin

1. Giới thiệu

Kotlin thường dùng thư viện Gson, Moshi, hoặc kotlinx.serialization để làm việc với JSON.

2. Setup kotlinx.serialization

// build.gradle.kts plugins { kotlin("plugin.serialization") version "1.9.0" } dependencies { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0") }

3. Serialize Object to JSON

import kotlinx.serialization.* import kotlinx.serialization.json.* @Serializable data class User(val name: String, val age: Int) fun main() { val user = User("Alice", 25) val json = Json.encodeToString(user) println(json) // {"name":"Alice","age":25} }

4. Deserialize JSON to Object

import kotlinx.serialization.* import kotlinx.serialization.json.* @Serializable data class User(val name: String, val age: Int) fun main() { val jsonString = """{"name":"Bob","age":30}""" val user = Json.decodeFromString<User>(jsonString) println(user) // User(name=Bob, age=30) }

5. Nested Objects

@Serializable data class Address(val city: String, val country: String) @Serializable data class Person(val name: String, val address: Address) fun main() { val json = """ { "name": "Alice", "address": { "city": "Hanoi", "country": "Vietnam" } } """.trimIndent() val person = Json.decodeFromString<Person>(json) println(person.address.city) // Hanoi }

6. Lists và Arrays

@Serializable data class User(val name: String) fun main() { val json = """[{"name":"Alice"},{"name":"Bob"}]""" val users = Json.decodeFromString<List<User>>(json) users.forEach { println(it.name) } }

7. Optional và Default Values

@Serializable data class Config( val host: String = "localhost", val port: Int = 8080, val debug: Boolean = false ) fun main() { val json = """{"host":"api.example.com"}""" val config = Json.decodeFromString<Config>(json) println(config.host) // api.example.com println(config.port) // 8080 (default) }

8. Custom JSON Settings

val json = Json { prettyPrint = true ignoreUnknownKeys = true isLenient = true encodeDefaults = true } @Serializable data class User(val name: String) fun main() { val user = User("Alice") println(json.encodeToString(user)) // Pretty printed output }

9. Custom Serializers

import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* object DateAsLongSerializer : KSerializer<Date> { override val descriptor = PrimitiveSerialDescriptor("Date", PrimitiveKind.LONG) override fun serialize(encoder: Encoder, value: Date) { encoder.encodeLong(value.time) } override fun deserialize(decoder: Decoder): Date { return Date(decoder.decodeLong()) } } @Serializable data class Event( val name: String, @Serializable(with = DateAsLongSerializer::class) val date: Date )

10. Với Gson (Alternative)

// Add: implementation("com.google.code.gson:gson:2.10.1") import com.google.gson.Gson data class User(val name: String, val age: Int) fun main() { val gson = Gson() // To JSON val user = User("Alice", 25) val json = gson.toJson(user) // From JSON val parsed = gson.fromJson(json, User::class.java) println(parsed) }

📝 Tóm tắt

  • @Serializable annotation cho data classes
  • Json.encodeToString() object → JSON
  • Json.decodeFromString() JSON → object
  • Custom Json settings với Json { }
  • Default values cho optional fields
  • ignoreUnknownKeys = true cho flexible parsing
Last updated on