kotlin json parser example with retrofit

Kotlin Android JSON Parsing Tutorial + Retrofit + RecyclerView

JSON stands for JavaScript Object Notation. It is data exchange format.

If your Mobile Application needs to get/exchange data with your application server that data has to be in a proper format so both platforms understand what the data is and how to parse it.

JSON is built on two structures JSON Array and JSON Objects.

All the values in JSON are in Key/Value pair.

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.

We will Cover 2 Different JSON Parsing Examples.

Manually Parsing JSON in Kotlin Android using GSON Library and org.json package.

Parsing JSON using GSON + JSON Parser Plugin + JSON Data Class Mapping.

JSON Parser Example using org.json

val sampleJson = """
      [
{
  "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"
}]
"""

Let say we have above JSON Array which has one JSON object.

We will iterate through above JSON Array and will parse each JSON Object on each index.

Kotlin Code Example

If we want to get a specific value for example “title” from JsonObject.

var jsonArray = JSONArray(sampleJson)
for (jsonIndex in 0..(jsonArray.length() - 1)) {
    Log.d("JSON", jsonArray.getJSONObject(jsonIndex).getString("title"))
}

Output:

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Converting JSON Object to String

If you want to convert above JSON value into String in Kotlin.

var jsonArray = JSONArray(sampleJson)

for (jsonIndex in 0..(jsonArray.length() - 1)) {
    Log.d("JSON", jsonArray.getJSONObject(jsonIndex).toString())
}

JSON Parsing using GSON Library Kotlin Example

If you want to use GSON library for parsing JSON manually.

Here we are passing sample JSON and expected Type in which we want to format JSON data.

Because we have JSON Array so the second argument is JsonArray::class.java.

var jsonArray2 = Gson().fromJson(sampleJson, JsonArray::class.java)
for (jsonIndex in 0..(jsonArray2.size() - 1)) {
    Log.d("JSON2", jsonArray.getJSONObject(jsonIndex).getString("title"))
}

Automated JSON Parser Example Kotlin Android

This time we will make API Call using the Retrofit library.

We will receive JSON response.

We will parse that JSON response into Kotlin Data Class. And will show JSON response in Android RecyclerView.

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

 

Posts created 24

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