Sling Academy
Home/Kotlin/How to Map API Responses to Kotlin Data Classes

How to Map API Responses to Kotlin Data Classes

Last updated: November 30, 2024

Mapping API responses to data classes in Kotlin is a fundamental task when working with REST APIs. Data classes provide a simple syntax and immutability, which makes them an excellent choice for modeling API responses. In this article, we will walk through how to parse JSON responses and map them to Kotlin data classes using popular libraries like Gson and Moshi.

Understanding API Responses

When you make an HTTP request to an API, the server responds with data usually in JSON format. The response might look something like this:

{
  "id": 1,
  "name": "John Doe",
  "email": "[email protected]"
}

We'll map this JSON to a Kotlin data class.

Define the Kotlin Data Class

The first step is to define a data class that has properties corresponding to the keys in the JSON object. Here is how you can define a Kotlin data class:

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

Mapping with Gson

Gson is a popular library for converting JSON strings to objects. First, add the Gson dependency to your project's build.gradle file:

implementation 'com.google.code.gson:gson:2.8.8'

You can then use Gson to deserialize the JSON into a User object:

import com.google.gson.Gson

fun parseUserWithGson(json: String): User {
    val gson = Gson()
    return gson.fromJson(json, User::class.java)
}

val json = """{
  "id": 1,
  "name": "John Doe",
  "email": "[email protected]"
}"""

val user: User = parseUserWithGson(json)
println(user)

Mapping with Moshi

Moshi is another library for JSON parsing in Kotlin, which also supports Kotlin's native data classes and null safety. First, add the Moshi dependency:

implementation 'com.squareup.moshi:moshi:1.13.0'

Now, use Moshi to parse the JSON:

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory

fun parseUserWithMoshi(json: String): User {
    val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()
    val jsonAdapter = moshi.adapter(User::class.java)
    return jsonAdapter.fromJson(json)!!
}

val json = """{
  "id": 1,
  "name": "John Doe",
  "email": "[email protected]"
}"""

val user: User = parseUserWithMoshi(json)
println(user)

Conclusion

In this article, we've demonstrated how to map JSON API responses to Kotlin data classes using Gson and Moshi. Each of these libraries has its own advantages and can be chosen based on the specific needs of your project, such as serialization speed, flexibility, or ease of use with Kotlin features.

Next Article: Kotlin: Handling Authentication in API Calls (Basic, Bearer, OAuth)

Previous Article: Working with XML Responses in Kotlin APIs

Series: Networking in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin