Skip to main content

How to use Gson converter with Retrofit in Kotlin Android

How to use Gson converter with Retrofit in Kotlin Android.

Here's a step-by-step tutorial on how to use Gson converter with Retrofit in Kotlin for Android:

  1. Start by adding the necessary dependencies to your project. Open your project's build.gradle file and add the following lines inside the dependencies block:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  1. Create a data class that represents the structure of the JSON response you expect from your API. For example, let's say you have an API endpoint that returns a list of users. You can create a data class like this:
data class User(
val id: Int,
val name: String,
val email: String
)
  1. Next, create an interface that defines your API endpoints. Annotate each endpoint method with appropriate HTTP method annotations (e.g., @GET, @POST, etc.), and specify the expected response type as Call or Observable. For example:
interface ApiService {
@GET("/users")
fun getUsers(): Call<List<User>>
}
  1. Now, create a Retrofit instance using the Retrofit.Builder class. Configure the base URL of your API and add the Gson converter factory. For example:
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build()

val apiService = retrofit.create(ApiService::class.java)
  1. Finally, make API calls using the generated service instance. For example, to fetch the list of users, you can do:
apiService.getUsers().enqueue(object : Callback<List<User>> {
override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
if (response.isSuccessful) {
val users = response.body()
// Do something with the list of users
} else {
// Handle error response
}
}

override fun onFailure(call: Call<List<User>>, t: Throwable) {
// Handle network failure
}
})

That's it! You have successfully used Gson converter with Retrofit in Kotlin for Android. Gson will automatically convert the JSON response into a list of User objects for you to use in your app.

Note: Make sure to wrap your API calls in appropriate try-catch blocks and handle any exceptions that may occur during network operations.