JSON Parsing in Android

JSON Parsing in Android
– JSON stands for JavaScript Object Notation.
– It’s a format for data exchange and storage and compared to XML, this can be simple and straightforward parse inforamtion interchange format.
– It’s extensively used for data exchange between the device and server in android app.
– It’s a light-weight data-interchange format that’s language independent.

JSON Structures in Android
Two kinds of brackets uses for JSON:
1. [] – To declare the weather of Array in JSON, they’re written in square brackets.
2. {} –  to make JSON objects, the weather are written in curly brackets.

JSON is following the below structures.
1. JSON Objects – Inside the curly brackets are called Objects.

{  
  "employee": {  
    "name": "Vaibhav",   
    "salary": 56000,   
    "married": false  
  }  
}

2. JSON Array – List of values, called Arrays.

["0", "1", "23", "45", "65", "55", "95"]

3. JSON Key-Value – Data is stored as a pair of keys and values. Here the keys will be a reputation, a number that the values will be Vaibhav, 97979797 etc.

Follow the below step for implementation for JSON Parsing.

1. Create new project for android studio.
2. Then add your .json file from raw folder.
3. Add to activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/seeAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="See All"
        android:padding="10dp"
        android:gravity="end"
        android:layout_gravity="end"
        android:textColor="@color/black"
        android:layout_marginHorizontal="15dp"
        android:textSize="20sp" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

4. Add to Recyclerview Item layout row_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="220dp"
    android:minHeight="70dp"
    android:layout_margin="10dp"
    app:cardCornerRadius="10dp"
    android:elevation="5dp">

    <ImageView
        android:id="@+id/ivImage"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:gravity="center_horizontal"
        android:layout_marginBottom="20dp"
        android:layout_gravity="bottom"
        android:textColor="@color/white"
        android:textSize="20sp" />
</androidx.cardview.widget.CardView>

5. Add to java class HomeActivity.class

class HomeActivity : AppCompatActivity() {
    lateinit var binding: ActivityHomeBinding
    var url: ArrayList<String> = ArrayList()
    var image: ArrayList<String> = ArrayList()
    var title: ArrayList<String> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHomeBinding.inflate(layoutInflater)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
        setContentView(binding.root)
        binding.seeAll.setOnClickListener {
            Toast.makeText(this, "Coming Soon", Toast.LENGTH_SHORT).show()
        }
        try {
            val array = JSONArray(loadJSONFromAsset())
            for (i3 in 0 until array.length()) {
                val mainArray = array.getJSONObject(i3)
                val dataArray = mainArray.getJSONArray("data")
                for (i in 0 until dataArray.length()) {
                    val dataDetail = dataArray.getJSONObject(i)
                    val listArray = dataDetail.getJSONArray("list")
                    for (i2 in 0 until listArray.length()) {
                        val listDetail = listArray.getJSONObject(i2)
                        url.add(listDetail.getString("url"))
                        title.add(listDetail.getString("title"))
                        image.add(listDetail.getString("image"))
                    }
                }
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val customAdapter = CustomAdapter(this@HomeActivity, url, image, title)
//        binding.recyclerView.layoutManager =
//            GridLayoutManager(this, 2, RecyclerView.VERTICAL, false)
        val staggeredGridLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        staggeredGridLayoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        binding.recyclerView.layoutManager = staggeredGridLayoutManager
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.adapter = customAdapter
    }

    private fun loadJSONFromAsset(): String {
        val json: String?
        try {
            val inputStream = assets.open("response.json")
            val size = inputStream.available()
            val buffer = ByteArray(size)
            val charset: Charset = Charsets.UTF_8
            inputStream.read(buffer)
            inputStream.close()
            json = String(buffer, charset)
        } catch (ex: IOException) {
            ex.printStackTrace()
            return ""
        }
        return json
    }
}

6. Add to adapter CustomAdapter.class

package com.jsonget.gettingjson

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class CustomAdapter(
    private var context: Context,
    private var url: ArrayList<String>,
    private var image: ArrayList<String>,
    private var title: ArrayList<String>
) :
    RecyclerView.Adapter<CustomAdapter.MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false)
        return MyViewHolder(v)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.name.text = title[position]
        Glide.with(context).load(image[position]).into(holder.image)
    }

    override fun getItemCount(): Int {
        return url.size
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var name: TextView = itemView.findViewById<View>(R.id.tvName) as TextView
        var image: ImageView = itemView.findViewById<View>(R.id.ivImage) as ImageView
    }
}

7. Output

 

Submit a Comment

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

Subscribe

Select Categories