Retrofit Android Example JSON Parser in Kotlin

Retrofit android is a type-safe HTTP client for Android and Java. Retrofit is a REST Client for Java, Android, and Kotlin by Square inc under Apache 2.0 license. With this library or module used the in-app app for server smooth connection, like sing in sing up or downloading-uploading data.

Retrofit android example Json parser in kotlin

Why Retrofit library? Because it will save your development time and also you can keep your code developer-friendly. Retrofit has given almost all the APIs to make a server call and to receive a response. Internally they also use GSON to do the parsing.

Let’s build an Example of Retrofit Android Example JSON Parser in Kotlin

In this example, we are using a simple example to connect your android application to the server using the Retrofit 2 library. Let’s start building the application with simple and few steps.

Step 1. Create a new application, check this tutorial Build Your First Android App in Kotlin.
Step 2. In dependencies Gradle build.gradle (Module: app), 

Add GSON and retrofit 2 dependencies, GSON retrofit dependency is convertersResponseBody  to JSON object.

dependencies {
    ....
    compile 'com.squareup.retrofit2:retrofit:2.4.0'
    compile 'com.squareup.retrofit2:converter-gson:2.4.0'
}

Retrofit requires at minimum Java 7 or Android 2.3., After adding the library just sync your project.

Step 3. For this example, we need an API

So we are using GitHub search API. https://api.github.com/search/users?q=rohitkan

Here is response formate from API, data may change time to time depends on API.

{
  "total_count": 6,
  "incomplete_results": false,
  "items": [
    {
      "login": "rohitkandhal",
      "id": 2447448,
      "node_id": "MDQ6VXNlcjI0NDc0NDg=",
      "avatar_url": "https://avatars1.githubusercontent.com/u/2447448?v=4",
      "gravatar_id": "",
      "url": "https://api.github.com/users/rohitkandhal",
      "html_url": "https://github.com/rohitkandhal",
      "followers_url": "https://api.github.com/users/rohitkandhal/followers",
      "following_url": "https://api.github.com/users/rohitkandhal/following{/other_user}",
      "gists_url": "https://api.github.com/users/rohitkandhal/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/rohitkandhal/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/rohitkandhal/subscriptions",
      "organizations_url": "https://api.github.com/users/rohitkandhal/orgs",
      "repos_url": "https://api.github.com/users/rohitkandhal/repos",
      "events_url": "https://api.github.com/users/rohitkandhal/events{/privacy}",
      "received_events_url": "https://api.github.com/users/rohitkandhal/received_events",
      "type": "User",
      "site_admin": false,
      "score": 62.782448
    },
    { ...}
    ....
]}
Step 4. Create 2 models class

Because the json itself is an array of your items objects (Retrofit can convert between json arrays to java lists). For the second json, you have just an object and not an array. For this, you need to create another call with another model that maps to that json. Let’s assume you’ve named the model UsersList. Here’s how the call could look like:

1st UsersList model, Top level – List of Users

package `in`.eyehunt.retrofitandroidexamplekotlin
import com.google.gson.annotations.SerializedName
class UsersList {
    @SerializedName("items")
    var users: List<Users>? = null
}

2nd Users model, second level  – Users objects

package `in`.eyehunt.retrofitandroidexamplekotlin
class Users {
    var id: Int = 0
    var login: String = ""
    var score: Float = 0.0f
}
Step 4. Create API interface
package in.eyehunt.retrofitandroidexamplekotlin;
import retrofit2.Call;
import retrofit2.http.GET;

public interface Api {
    //urls 
    @GET("users?q=rokano")
    Call<UsersList> getUsers();
}
Step 5. add following code in resource layout file main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.eyehunt.retrofitandroidexamplekotlin.MainActivity">

    <TextView
        android:id="@+id/tv_users"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:scrollbars="vertical"
        android:text="Hello World!"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.051"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.032" />

</android.support.constraint.ConstraintLayout>
Step 6. add following code in MainActivity kotlin class.
package `in`.eyehunt.retrofitandroidexamplekotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : AppCompatActivity() {
    val BASE_URL = "https://api.github.com/search/"
    var tv_user: TextView? = null
    var str:String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv_user = findViewById(R.id.tv_users)
        getUsers()
    }
    // function to call server and update ui
    fun getUsers() {
        var retrofit: Retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        var api = retrofit.create(Api::class.java)
        var call = api.users
        call.enqueue(object : Callback<UsersList> {

            override fun onResponse(call: Call<UsersList>?, response: Response<UsersList>?) {
                var usres = response?.body()
                var user = usres?.users
                var length = user!!.size

                for (i in 0 until length) {
                    str = str + "\n" + user.get(i).id + " " + user.get(i).login
                }

                tv_user!!.text = str
            }

            override fun onFailure(call: Call<UsersList>?, t: Throwable?) {
                Log.v("Error", t.toString())
            }
        })
    }
}
Step 7. add internet permissions in manifest.xml, for internet connection

Without Internet permission, Android application will raise an exception or error.

<manifest>
    <uses-permission android:name="android.permission.INTERNET"/>
    ....
</manifest>
Step 8. Run the application, in the emulator or on your android device

Output screenshot Retrofit android example JSONparser in kotlin

Retrofit android example Json parser in kotlin tutorial

Download Retrofit android JSON parser example source code  :

https://github.com/EyeHunts/RetrofitAndroidExamplekotlin

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in Kotlin

Retrofit CONVERTERS

By default, Retrofit can only deserialize HTTP bodies into OkHttp’s ResponseBody type and it can only accept its RequestBody type for @Body. You can converters can add to support other types. like

  • Gson: com.squareup.retrofit2:converter-gson
  • Simple XML: com.squareup.retrofit2:converter-simplexml

Source: http://square.github.io/retrofit/


3 thoughts on “Retrofit Android Example JSON Parser in Kotlin

  1. Hi,
    Step 4 must be :
    import retrofit2.Call
    import retrofit2.http.GET

    interface Api {
    //urls
    @GET(“users?q=rokano”)
    fun getUsers() : Call
    }
    If you’re in Kotlin, right ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.