Kotlin Multiplatform: Data Serialization and Networking Made Simple
Data Serialization and Networking Made Simple

Kotlin Multiplatform: Data Serialization and Ktor Networking Made Simple

Efficient data handling and networking are the backbone of modern cross-platform apps. In Kotlin Multiplatform (KMP), tools like kotlinx.serialization and Ktor Client streamline these tasks, enabling seamless data exchange across Android, iOS, and web. This chapter dives into serialization, HTTP requests, and asynchronous operations in KMP—all while keeping your codebase clean and platform-agnostic.

1. Serialization with kotlinx.serialization

Kotlin’s kotlinx.serialization library simplifies converting objects to formats like JSON, ProtoBuf, or XML.

Setup in KMP

Add these dependencies to build.gradle.kts:

// Shared module  
plugins {  
    kotlin("plugin.serialization") version "1.9.20"  
}  

dependencies {  
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")  
}  

Define a Serializable Class

import kotlinx.serialization.Serializable  

@Serializable  
data class User(val id: Int, val name: String, val email: String)  

Convert Between JSON and Objects

  • Serialize to JSON:val user = User(1, "Alex", "alex@example.com") val json = Json.encodeToString(user) // Output: {"id":1,"name":"Alex","email":"alex@example.com"}
  • Deserialize from JSON:val jsonData = """{"id":1,"name":"Alex","email":"alex@example.com"}""" val userObj = Json.decodeFromString<User>(jsonData)

Handling Missing Fields:

val json = Json { ignoreUnknownKeys = true } // Skips unknown keys during deserialization  

2. Networking with Ktor Client

Ktor is a multiplatform HTTP client for handling API requests.

Setup Ktor in KMP

Add platform-specific dependencies:

// Shared module  
dependencies {  
    implementation("io.ktor:ktor-client-core:2.3.6")  
    implementation("io.ktor:ktor-client-content-negotiation:2.3.6")  
    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.6")  
}  

// Platform modules  
androidMain {  
    implementation("io.ktor:ktor-client-okhttp:2.3.6")  
}  
iosMain {  
    implementation("io.ktor:ktor-client-darwin:2.3.6")  
}  
jsMain {  
    implementation("io.ktor:ktor-client-js:2.3.6")  
}  

Create an HTTP Client

import io.ktor.client.*  
import io.ktor.client.plugins.contentnegotiation.*  

val httpClient = HttpClient {  
    install(ContentNegotiation) {  
        json(Json { ignoreUnknownKeys = true })  
    }  
}  

Fetch Data from an API

suspend fun fetchUser(): User {  
    return httpClient.get("https://api.example.com/user/1").body()  
}  

// Usage  
suspend fun printUser() {  
    val user = fetchUser()  
    println(user) // User(id=1, name=Alex, email=alex@example.com)  
}  

Error Handling

suspend fun fetchUserSafe(): User? {  
    return try {  
        httpClient.get("https://api.example.com/user/1").body()  
    } catch (e: ClientRequestException) {  
        println("Error: ${e.response.status}")  
        null  
    } catch (e: ServerResponseException) {  
        println("Server error: ${e.response.status}")  
        null  
    }  
}  

3. Working with Data Formats

KMP supports multiple formats via kotlinx.serialization:

FormatUse CaseDependency
JSONWeb APIskotlinx-serialization-json
ProtoBufHigh-performance systemskotlinx-serialization-protobuf
CBORCompact binary datakotlinx-serialization-cbor

ProtoBuf Example

// Add dependency  
implementation("org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.6.0")  

// Serialize  
val data = SensorData(1675038210, 24.5)  
val bytes: ByteArray = ProtoBuf.encodeToByteArray(data)  

// Deserialize  
val decodedData = ProtoBuf.decodeFromByteArray<SensorData>(bytes)  

4. Asynchronous Operations with Coroutines

Kotlin Coroutines handle async tasks without blocking the main thread.

Parallel Requests

suspend fun fetchMultipleUsers(): List<User> = coroutineScope {  
    val user1 = async { fetchUser() }  
    val user2 = async { fetchUser() }  
    listOf(user1.await(), user2.await())  
}  

Thread Management

PlatformDispatcher
AndroidDispatchers.Main
iOSMainScope().launch
Shared CodeDispatchers.Default

Best Practices:

  • Use Dispatchers.IO for network calls.
  • Wrap risky operations in try-catch.

Key Takeaways

  1. Use kotlinx.serialization for JSON/ProtoBuf conversions.
  2. Ktor Client simplifies cross-platform HTTP requests.
  3. Handle errors gracefully with Kotlin Coroutines.

  • Target keywords: “Kotlin Multiplatform Networking,” “Ktor Client KMP,” “kotlinx.serialization.”
  • Link to Ktor documentation for authority.

Mobile Application Developer with over 12 years of experience crafting exceptional digital experiences.I specialize in delivering high-quality, user-friendly mobile applications across diverse domains including EdTech, Ride Sharing, Telemedicine, Blockchain Wallets, and Payment Gateway integration.My approach combines technical expertise with collaborative leadership, working seamlessly with analysts, QA teams, and engineers to create scalable, bug-free solutions that exceed expectations.Let's connect and transform your ideas into remarkable mobile experiences.
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments