kotlin json parser example with retrofit

Kotlin Android JSON Parsing Tutorial + Retrofit + RecyclerView

In this tutorial, we will learn how to parse JSON Objects and JSON Arrays in Android using Kotlin.

What we will learn in this tutorial:

  • We will consume API which will return JSON Array.
  • We will use Retrofit library for making API call.
  • We will parse JSON response and map it to Kotlin data class.
  • We will show JSON response in RecyclerView.

Sample JSON

We will make API call using Retrofit2.

We will get below JSON data from this URL:- https://jsonplaceholder.typicode.com/posts/

We will be parsing this JSON and will show this in Android RecyclerView.

This is simple JSON Array which returns a list of POST’S.

[  Represents JSON Array.

{ Represent JSON Object.

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },
  {
    "userId": 1,
    "id": 4,
    "title": "eum et est occaecati",
    "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
  }
]

Let’s create a new Android Project.

  • Do not forget to check Add Kotlin Support in Android Studio while creating new project.

Add Internet permission in the Manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.developine.kotlinjsonparsing">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Add Retrofit + RecyclerView + GSON + RxAndroid dependencies.

//RETROFIT ...  NETWORK LIBRARY
implementation 'com.squareup.retrofit2:retrofit:2.4.0'

// RETROFIT .. CONVERTER & ADAPTER
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

// RX-ANDROID
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'

// RECYCLERVIEW
implementation 'com.android.support:recyclerview-v7:27.1.1'

Add Kotlin Android Extensions plugin in module build.gradle file.

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

Create new data class for JSON  response Mapping to Kotlin class objects.

I used a plugin in Android studio JSON to Kotlin Data class Converter.

Which automatically converted above JSON List to the below Kotlin Data Class Post.

convert json to kotlin data class android studio
Converting JSON to Kotlin Data Class

After clicking Make button, It will create Post class like below.

import com.google.gson.annotations.SerializedName


data class Post(
      @SerializedName("userId") val userId: Int,
      @SerializedName("id") val id: Int,
      @SerializedName("title") val title: String,
      @SerializedName("body") val body: String
)

Adding RecyclerView in the project.

Before making Retrofit API call we are supposed to add RecyclerView in our MainActivity.

We also have to create RecyclerView adapter class and adapter layout file.

 

activity_main.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=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv__list_posts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

Creating RecyclerView item layout file.

Create new layout file and name it post_item_layout.xml which will be used to display single post item in RecyclerView.

post_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">
    
    <TextView
        android:id="@+id/txtPostTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textSize="16sp" />

    <TextView

        android:id="@+id/txtPostBody"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="22sp"
        android:textStyle="bold" />

</LinearLayout>

Creating RecyclerView Adapter class.

class PostItemAdapter(val postList: List<Post>, val context: Context) : 
      RecyclerView.Adapter<PostItemAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.post_item_layout,
                          parent, false))
    }

    override fun getItemCount(): Int {
        return 10
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.itemView.txtPostTitle.text = postList.get(position).title
        holder.itemView.txtPostBody.text = postList.get(position).body

    }
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
}

Create API Interface for Retrofit.

Create new Interface and name it INetworkAPI.

This is to tell Retrofit about API:

  • HTTP method type  ( @GET ) in our case.
  • Ressponse Type      ( Observable<List<Post>>)
  • API URL                   ( posts/ )

API Base URL is : https://jsonplaceholder.typicode.com/

INetworkAPI.kt

import io.reactivex.Observable
import retrofit2.http.GET

interface INetworkAPI {

    @GET("posts/")
    fun getAllPosts(): Observable<List<Post>>
}

Downloading and Parsing JSON using Retrofit + Kotlin.

Open MainActivity.kt.

Here we are:

  • Building Retrofit Client object.
  • Specifying GSON as a converter factory.
  • Making API Call using INetworkAPI Interface.
  • Showing list of Posts in Android RecyclerView Adapter.
MainActivity.kt

import com.google.gson.GsonBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.internal.schedulers.IoScheduler
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rv__list_posts.layoutManager = LinearLayoutManager(this)

        val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl("https://jsonplaceholder.typicode.com/").build()

        val postsApi = retrofit.create(INetworkAPI::class.java)

        var response = postsApi.getAllPosts()

        response.observeOn(AndroidSchedulers.mainThread()).subscribeOn(IoScheduler()).subscribe {
            rv__list_posts.adapter = PostItemAdapter(it, this)
        }

    }
}

Output:

We are only showing post title and body in RecyclerView.

Kotlin JSON parsing example using retrofit and gson
Kotlin JSON parsing example

If you have learned something from this article, share it 🙂 or comment if you have any confusion.

copyright @ www.developine.com

 

Post created 22

One thought on “Kotlin Android JSON Parsing Tutorial + Retrofit + RecyclerView

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top