Kotlin Serialization
Converting Kotlin objects to JSON and other formats
📦 What is Kotlin Serialization?
Kotlin Serialization is a compiler plugin that automatically generates serialization code for your data classes. Convert objects to JSON, XML, or other formats effortlessly and safely.
@Serializable
data class Person(val name: String, val age: Int)
val person = Person("Alice", 25)
val json = Json.encodeToString(person)
// Result: {"name":"Alice","age":25}
Serialization Features
JSON Support
Built-in JSON serialization
Json.encodeToString(data)
Json.decodeFromString<Person>(json)
Type Safety
Compile-time type checking
@Serializable
data class User(val id: Int)
Customization
Custom serializers and names
@SerialName("user_name")
val userName: String
Multiple Formats
JSON, XML, ProtoBuf support
ProtoBuf.encodeToByteArray(data)
Xml.encodeToString(data)
🔹 Basic Serialization
Mark your data classes with @Serializable:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class Book(
val title: String,
val author: String,
val pages: Int,
val published: Boolean = false
)
fun main() {
val book = Book("1984", "George Orwell", 328, true)
// Serialize to JSON
val json = Json.encodeToString(book)
println(json)
// Deserialize from JSON
val bookFromJson = Json.decodeFromString<Book>(json)
println(bookFromJson)
}
Output:
{"title":"1984","author":"George Orwell","pages":328,"published":true}
Book(title=1984, author=George Orwell, pages=328, published=true)
🔹 Custom Property Names
Use @SerialName to customize JSON property names:
@Serializable
data class User(
@SerialName("user_id")
val id: Int,
@SerialName("full_name")
val name: String,
@SerialName("email_address")
val email: String
)
fun main() {
val user = User(1, "John Doe", "[email protected]")
val json = Json.encodeToString(user)
println(json)
}
Output:
{"user_id":1,"full_name":"John Doe","email_address":"[email protected]"}
🔹 Nested Objects and Lists
Serialize complex nested structures:
@Serializable
data class Address(val street: String, val city: String, val zipCode: String)
@Serializable
data class Company(
val name: String,
val employees: List<Employee>,
val address: Address
)
@Serializable
data class Employee(val name: String, val position: String, val salary: Double)
fun main() {
val company = Company(
name = "Tech Corp",
employees = listOf(
Employee("Alice", "Developer", 75000.0),
Employee("Bob", "Designer", 65000.0)
),
address = Address("123 Main St", "Tech City", "12345")
)
val json = Json {
prettyPrint = true
}.encodeToString(company)
println(json)
}
Output:
{
"name": "Tech Corp",
"employees": [
{
"name": "Alice",
"position": "Developer",
"salary": 75000.0
},
{
"name": "Bob",
"position": "Designer",
"salary": 65000.0
}
],
"address": {
"street": "123 Main St",
"city": "Tech City",
"zipCode": "12345"
}
}
🔹 Optional and Default Values
Handle optional properties and default values:
@Serializable
data class Product(
val id: Int,
val name: String,
val price: Double,
val description: String? = null, // Optional
val inStock: Boolean = true // Default value
)
fun main() {
// JSON with missing optional fields
val json = """{"id":1,"name":"Laptop","price":999.99}"""
val product = Json.decodeFromString<Product>(json)
println(product)
// Serialize with all fields
val fullProduct = Product(2, "Mouse", 29.99, "Wireless mouse", false)
println(Json.encodeToString(fullProduct))
}
Output:
Product(id=1, name=Laptop, price=999.99, description=null, inStock=true)
{"id":2,"name":"Mouse","price":29.99,"description":"Wireless mouse","inStock":false}