Welcome to this comprehensive Kotlin JSON Serialization tutorial! In this lesson, we'll dive deep into the world of JSON serialization, an essential skill for any Kotlin developer working with APIs or data storage. Let's get started!
JSON (JavaScript Object Notation) is a lightweight data interchange format commonly used for communication between a client and server. JSON Serialization is the process of converting Kotlin objects into JSON format and vice versa. This enables us to easily exchange data between different systems.
To work with JSON in Kotlin, we need to add the following dependencies to our build.gradle file:
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"
}Before we dive into serialization, let's take a quick look at Kotlin's data classes. Data classes are a concise way to define classes with properties and getters and setters for free. Here's an example:
data class User(val name: String, val age: Int)In this example, a User data class is defined with two properties: name and age.
Now that we understand data classes, let's see how we can convert them to JSON and vice versa.
To serialize a Kotlin object to JSON, we can use the json object provided by the kotlinx-serialization-json library. Here's an example:
import kotlinx.serialization.json.Json
fun main() {
val user = User("John Doe", 30)
val json = Json.encodeToString(user)
println(json)
}This code creates a User object, converts it to JSON using the json.encodeToString() function, and then prints the JSON string.
To deserialize JSON back into Kotlin objects, we can use the json.decodeFromString() function. Here's an example:
import kotlinx.serialization.json.Json
fun main() {
val json = "{\"name\": \"Jane Doe\", \"age\": 28}"
val user = Json.decodeFromString(json)
println(user)
}This code defines a JSON string, converts it back into a User object using the json.decodeFromString() function, and then prints the object.
Let's create a simple REST API that allows us to create and retrieve users. We'll use Ktor for building the API.
First, add the Ktor dependency to your build.gradle file:
dependencies {
implementation "io.ktor:ktor-server-core:1.4.2"
implementation "io.ktor:ktor-serialization-json:1.4.2"
}Next, create a UserController.kt file with the following content:
import io.ktor.application.*
import io.ktor.features.json.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.serialization.json.*
import kotlinx.serialization.json.Json
data class User(val id: Int, val name: String, val age: Int)
class UserController(private val users: MutableList<User>) {
suspend fun createUser(call: ApplicationCall) {
val user = call.receive<User>()
users.add(user)
call.respond(HttpStatusCode.Created)
}
suspend fun getUser(call: ApplicationCall) {
val id = call.parameters["id"]?.toIntOrNull()
if (id == null) {
call.respondText("ID is required", status = HttpStatusCode.BadRequest)
return
}
val user = users.find { it.id == id }
if (user == null) {
call.respondText("User not found", status = HttpStatusCode.NotFound)
return
}
call.respond(user)
}
}
fun main() {
embeddedServer(Netty, port = 8080) {
install(ContentNegotiation) {
json()
}
route {
post("/users") {
val userController = UserController(mutableListOf())
userController.createUser(this)
}
get("/users/{id}") {
val userController = UserController(mutableListOf())
userController.getUser(this)
}
}
}.start(WaitStrategy.LEAST_ connections = 16, time = 60_000L)
}This code creates a simple API with endpoints for creating and retrieving users. Run the API and test it using a tool like Postman or curl.
What is JSON?
And that's a wrap for our Kotlin JSON Serialization tutorial! By now, you should have a solid understanding of JSON and how to use it with Kotlin. Happy coding! 🎉