• Products
    • IT Services
  • Pricing
    • Checkout
  • Blog
    • Kotlin
    • Android
    • Windows
    • Java
  • Contact Us
    • About Us
    • Careers
    • Reviews
  • Privacy Policy
    • Refund and Cancellation Policy
    • Terms of Service
    • Policy for Gsbiz Invoice
  • Stackoverflow
  • Github
  • Facebook
  • Twitter
  • Instagram

Kotlin JSON Parser Example for Android

  • Home
  • GALLEONSOFT TUTORIAL
  • Android
  • Kotlin JSON Parser Example for Android
Google reCAPTCHA safetynet
Android example for integrating captcha in android example
May 28, 2018
Published by Jigar Patel at June 10, 2018
Categories
  • Android
  • Kotlin
Tags
  • android
  • JSON
  • kotlin
Kotlin JSON Parser Example for Android

Hello fellas, In this article, we came up with Kotlin JSON Parser Example for Android. As we got many requests about Kotlin JSON parser tutorial, we finally get time to post it for our readers.

Introducing to JSON

JavaScript Object Notation is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the programming languages of many others. These properties make JSON an ideal data-interchange language.

Following are some useful facts about JSON:

  • JSON full form is JavaScript Object Notation (JSON).
  • JSON is a lightweight data-interchange format.
  • JSON is very easy for humans to read and write for rest-API or data send and receive.
  • JSON is simple for machines to parse and generate machine code.
  • The official JSON filenames use the extension .json and media type for JSON is application/JSON.
  • The JSON Type code is TEXT.

Kotlin JSON Parser Example for Android

JSON data is built on two structures like object{}, array[] A collection of name/value pairs realized as an object record JSON Object example: In this example name = full_name and value = Jigar Patel

{
	"full_name": "Jigar Patel"
}

An ordered list of object{} values means array[] JSON Array example: In this example first object = { “full_name” : “Jigar Patel” }

[{
	"full_name": "Jigar Patel"
}, {
	"full_name": "Ravi Patel"
}]

JSON Parsing in android Kotlin example tutorial for learning and how to parse JSON in Kotlin android using simple and easiest ways. What is the difference between {} and [] (Square brackets and Curly brackets)? The JSON data (node) will start and end with a curly bracket or square bracket. If JSON data is started with { and end with } means it’s JSON object and if JSON data is started with [ and end with ] means it’s JSON array. The JSON value can be a string in double quotes (” “), or a number, or true or false or null, or an object or an array. These structures can be nested on the collection of key/value pairs.

1. Create New Android Project

• Click on Android Studio Icon ( Open Android Studio ).
     ○ If you have already opened Android Studio from File ⇒ New Project.

• Start a new Android Studio Project. Then fill the displayed form.
     ○ See below-required details like this with an example.
     ○ Application name (Example: My AppName),
     ○ Company domain (Example: galleonsoft.com),
     ○ Project location (Example: C:\Users\JIGARPATEL\Desktop\Projects\MyAppName),
     ○ Package name (Example: com.galleonsoft.myappname),
     ○ Check Include Kotlin Support.

• Select the form factors and minimum SDK
     ○ Check Phone and Tablet.

• Add an Activity to Mobile you should Select Empty Activity.
     ○ You can select Basic Activity / Empty Activity. More options are available.

• Create a new empty activity.
     ○ Enter Activity Name (Example: MainActivity).
     ○ Enter Layout Name (Example: activity_main).

• Finish
     ○ Wait for few minutes to creating and building your projects.

 

2. Set XML Layout (UI)

Open the layout file of ( activity_jsonparser_kotlin.xml ) and add the below XML code.

 
<?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:orientation="vertical">

    <ProgressBar
        android:id="@+id/Pbar"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:visibility="gone" />

    <ListView
        android:id="@+id/Lv_developers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:dividerHeight="12dp" />


</LinearLayout>

3. Create the layout file for listview item row ( simple_listview_item.xml ) and add the below XML code.

 
<?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="wrap_content"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        android:textColor="@color/colorPrimary" />

    <TextView
        android:id="@+id/tv_city"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        android:textColor="@color/colorAccent" />

</LinearLayout>

4. Set Kotlin Android Code

Create a new class named ApiGetPostHelper.kt  This Object/Class GET And POST API. Also, it’s helps in others projects. This class required for HttpURLConnection Method. You can use alternatively Volley, Retrofit, etc. Create Kotlin object ApiGetPostHelper.kt and put the below code.

 
package com.galleonoft.jsonparser

import android.util.Log
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.UnsupportedEncodingException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.util.*
import javax.net.ssl.HttpsURLConnection

/**
 * Author: JIGAR PATEL.
 * Tutorial_URL: https://galleonsoft.com/tutorial/
 */

object ApiGetPostHelper {

    // Send Parameters method
    fun SendParams(reqURL: String, postDataParams: HashMap<String, String>?): String {

        val gsUrl: URL
        var resultString = ""
        try {
            gsUrl = URL(reqURL)

            val conn = gsUrl.openConnection() as HttpURLConnection
            conn.readTimeout = 7000
            conn.connectTimeout = 7000
            conn.requestMethod = "POST"
            conn.doInput = true
            conn.doOutput = true

            if (postDataParams != null) {
                // For Post encoded Parameters
                val os = conn.outputStream
                val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8"))
                writer.write(getPostDataString(postDataParams))
                writer.flush()
                writer.close()
                os.close()

            } else {
                conn.requestMethod = "GET"
            }


            val responseCode = conn.responseCode
            Log.i("responseCode: ", responseCode.toString() + "")
            if (responseCode == HttpsURLConnection.HTTP_OK) {

                val allTextResponse = conn.inputStream.bufferedReader().use(BufferedReader::readText)
                resultString = allTextResponse

            } else {
                resultString = ""
            }
        } catch (e: Exception) {
            resultString = ""
            e.printStackTrace()
        }

        return resultString

    }


    // Collect Params from HashMap and encode with url.
    @Throws(UnsupportedEncodingException::class)
    private fun getPostDataString(params: HashMap<String, String>): String {
        val result = StringBuilder()
        var first = true
        for ((key, value) in params) {
            if (first)
                first = false
            else
                result.append("&")

            result.append(URLEncoder.encode(key, "UTF-8"))
            result.append("=")
            result.append(URLEncoder.encode(value, "UTF-8"))
        }

        return result.toString()
    }

}

5. The Finally we are implementing the activity for android JSON app. Create Kotlin class JSONParserKotlinActivity.kt and put the below code. (It’s your Activity class like MainActivity.kt)

 
package com.galleonoft.jsonparser

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.SimpleAdapter
import android.widget.Toast
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*

class JSONParserKotlinActivity : AppCompatActivity() {

    lateinit var Lv_developers: ListView
    lateinit var Pbar: ProgressBar
    internal var developersList = ArrayList<HashMap<String, String>>()


    // Checking Internet is available or not
    private val isNetworkConnected: Boolean
        get() = (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo != null


    companion object {
        var GetPostJSONApi = "http://apps.galleonsoft.com/api-example/json-rest-api-example.php"
    }

    // Show BackButton on Actionbar
    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }

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

        // Show BackButton and Set custom Title on Actionbar
        val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar.title = "JSON Parser Kotlin Example"
            actionBar.setDisplayHomeAsUpEnabled(true)
            actionBar.setDisplayShowHomeEnabled(true)
        }

        // findViewById and set view id
        Pbar = findViewById(R.id.Pbar)
        Lv_developers = findViewById(R.id.Lv_developers)

        if (isNetworkConnected) {
            // Call AsyncTask for getting developer list from server (JSON Api)
            getDeveloper().execute()
        } else {
            Toast.makeText(applicationContext, "No Internet Connection Yet!", Toast.LENGTH_SHORT).show()
        }

    }


    @SuppressLint("StaticFieldLeak")
    inner class getDeveloper : AsyncTask<Void, Void, String>() {

        override fun onPreExecute() {
            // Show Progressbar for batter UI
            Pbar.visibility = View.VISIBLE
        }

        override fun doInBackground(vararg voids: Void): String {

            // Here is post Json api example
            val sendParams = HashMap<String, String>()
            // Send parameters and value on JSON api
            sendParams["Name"] = "JigarPatel"

            // Only Get JSON api send HashMap null see below comment example
            // return ApiGetPostHelper.SendParams(GetPostJSONApi, null);
            // Send the HttpPostRequest by HttpURLConnection and receive a Results in return string
            return ApiGetPostHelper.SendParams(GetPostJSONApi, sendParams)
        }

        override fun onPostExecute(results: String?) {
            // Hide Progressbar
            Pbar.visibility = View.GONE

            if (results != null) {
                // See Response in Logcat for understand JSON Results and make DeveloperList
                Log.i("onPostExecute: ", results)
            }

            try {
                // Create JSONObject from string response if your response start from Array [ then create JSONArray
                val rootJsonObject = JSONObject(results)
                val isSucess = rootJsonObject.getString("success")
                if (isSucess == "1") {
                    val developerArray = rootJsonObject.getString("developers")

                    val mJsonArray = JSONArray(developerArray)
                    for (i in 0 until mJsonArray.length()) {
                        // Get single JSON object node
                        val sObject = mJsonArray.get(i).toString()
                        val mItemObject = JSONObject(sObject)
                        // Get String value from json object
                        val Name = mItemObject.getString("Name")
                        val Age = mItemObject.getString("Age")
                        val City = mItemObject.getString("City")

                        // hash map for single jsonObject you can create model.
                        val mHash = HashMap<String, String>()
                        // adding each child node to HashMap key => value/data
                        // Now I'm adding some extra text in value
                        mHash["Name"] = "Name: $Name"
                        mHash["Age"] = "Age: $Age"
                        mHash["City"] = "City: $City"
                        // Adding HashMap pair list into developer list
                        developersList.add(mHash)
                    }

                    // This is simple Adapter (android widget) for ListView
                    val simpleAdapter = SimpleAdapter(
                            applicationContext, developersList,
                            R.layout.simple_listview_item,
                            // Add String[] name same as HashMap Key
                            arrayOf("Name", "Age", "City"),
                            intArrayOf(R.id.tv_name, R.id.tv_age, R.id.tv_city))

                    Lv_developers.adapter = simpleAdapter

                    Lv_developers.setOnItemClickListener { parent, view, position, id ->
                        Toast.makeText(applicationContext, "Selected item is " + position, Toast.LENGTH_SHORT).show()
                    }

                } else {
                    Toast.makeText(applicationContext, "No developers found!", Toast.LENGTH_SHORT).show()
                }


            } catch (e: JSONException) {
                Toast.makeText(applicationContext, "Something wrong. Try Again!", Toast.LENGTH_SHORT).show()
                e.printStackTrace()
            }

        }
    }


}

6. Open AndroidManifest.xml and We need to add INTERNET permission.

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

Then Run (Shift +F10) your android app and wait for build APK and see the screen with JSON Parser Api in android. If you have any trouble, follow github code from given link.

DOWNLOAD KOTLIN CODE

Conclusion: Hope you learned about Kotlin JSON parser example and its implementation for Android. Check more tutorials on GalleonSoft about Kotlin, Android Tutorials, Flutter example, Kotlin android etc.

 

Share
23
Jigar Patel
Jigar Patel
Hello, I am Jigar Patel. Now I am starting android Kotlin tutorial example for developers. So ready to share my wonderful knowledge.

Related posts

Google reCAPTCHA safetynet

Google-reCAPTCHA-safetynet android kotlin

May 28, 2018

Android example for integrating captcha in android example


Read more
Google reCAPTCHA safetynet

Google-reCAPTCHA-safetynet android kotlin

May 22, 2018

Kotlin tutorial for integrating Google’s reCAPTCHA on Android


Read more
tutorial-for-kotlin-android

tutorial-kotlin

May 17, 2018

Get Started Developing for Kotlin Android Tutorial 2019 with Android Studio


Read more
WhatsApp end to end encryption

WhatsApp end to end encryption

August 30, 2017

How to enable WhatsApp end to end encryption security


Read more

8 Comments

  1. Jan Balak says:
    November 29, 2018 at 10:38 PM

    I thing that in manifest file must be activity_jsonparser_kotlin, isn´t it?

    Reply
  2. luis says:
    December 3, 2018 at 9:16 AM

    sorry you could help me in the json file

    Reply
  3. AlbertBig says:
    December 18, 2018 at 6:08 PM

    Hello. I have checked your JSON Parser Tutorial.

    Reply
  4. hani says:
    March 17, 2019 at 5:15 AM

    not working , i get this toast something wrong. Try Again!

    Reply
  5. Will says:
    May 22, 2019 at 11:57 PM

    Imported the code from GitHub and ran on android studio, had a JSONexception (activated the “Something wrong. Try Again!” message. Is the JSON file still on the site?

    Reply
  6. Conner Luke says:
    September 15, 2019 at 3:53 AM

    how to convert json response to object pojo example. Great document for Kotlin Json parser.

    Reply
  7. Renna Drolet says:
    April 9, 2020 at 7:20 AM

    I think the admin of this website is actually working hard for his site, for the reason that here every data is quality based stuff.

    Reply
  8. Carol Zoltek says:
    April 19, 2020 at 8:34 AM

    First time visiting your kotlin android example website, I love your site!

    Reply

Leave a Reply Cancel reply

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

Recent Posts

  • Kotlin JSON Parser Example for Android
  • Android example for integrating captcha in android example
  • Kotlin tutorial for integrating Google’s reCAPTCHA on Android
  • Get Started Developing for Kotlin Android Tutorial 2019 with Android Studio
  • How to install Matlab R2018a
  • How to install Java 10 ( jdk 10 ) in windows

Categories

  • Android
  • Java
  • Kotlin
  • Windows

Subscribe Now

You can join our SLACK Channel
https://join.slack.com/t/galleonsoft/

 

© 2023 Galleonsoft. All Rights Reserved. Made by Galleonsoft.