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.