how-to-setup
To set up Kotlinx Serialization and use the @Serializable
annotation, follow these steps:
Step 1: Add Kotlinx Serialization Dependency
First, you need to add the Kotlinx Serialization dependency to your project. In your build.gradle.kts
(Kotlin DSL) file, include the following:
plugins {
kotlin("plugin.serialization") version "<kotlin_version>"
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:<version>")
}
Replace <kotlin_version>
with the version of Kotlin you are using and <version>
with the latest version of Kotlinx Serialization (e.g., 1.6.0
).
Step 2: Enable Serialization Plugin
In the plugins
block, ensure that you have the serialization
plugin enabled. This is necessary to process the @Serializable
annotations and generate the necessary serialization/deserialization code.
plugins {
kotlin("plugin.serialization") version "<kotlin_version>"
}
Step 3: Annotate Data Classes with @Serializable
You can now use the @Serializable
annotation in your Kotlin code. For example:
import kotlinx.serialization.Serializable
@Serializable
data class User(val name: String, val age: Int)
Step 4: Use Serialization and Deserialization Functions
With your class annotated, you can easily serialize and deserialize objects using the Json.encodeToString()
and Json.decodeFromString()
methods. Here's an example:
import kotlinx.serialization.json.Json
fun main() {
val user = User("Alice", 30)
// Serialize to JSON
val jsonString = Json.encodeToString(User.serializer(), user)
println(jsonString)
// Deserialize from JSON
val deserializedUser = Json.decodeFromString(User.serializer(), jsonString)
println(deserializedUser)
}
Step 5: Run Your Code
Once everything is set up, you can run your Kotlin program, and it will handle JSON serialization and deserialization seamlessly.
Key Takeaways:
- Add dependencies in
build.gradle.kts
. - Enable the
kotlinx-serialization
plugin. - Annotate your data classes with
@Serializable
. - Use the
Json
object for serialization and deserialization.
Let me know if you need further clarification!
Backlinks