JSON Parsing in Android Tutorial

In this article, we will learn, how to do JSON Parsing in Android. JSON stands for JavaScript Object Notation. It is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript).

JSON is built on two structures:

  • A collection of name/value pairs. It is also referred to as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. It is also referred to as an array, vector, list, or sequence.

JSON ELEMENTS:-

  1. JSON ARRAY- In a JSON file, square bracket ([) represents a JSON array
  2. JSON OBJECT- In a JSON file, curly bracket ({) represents a JSON object.
  3. KEY- A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object.
  4. VALUE- Each key has a value that could be a string, integer or double etc.

JSON PARSING IN ANDROID:-

There are 2 types:-  JSON Array and JSON Object.

  • If JSON starts from square bracket([) then, it is JSON Array. Use getJSONArray() method for this.
  • If JSON starts from curly braces({) then, it is a JSON Object. Use getJSONObject() method for this.

EXAMPLE OF JSON FILE-(ex1.json)

{
    "colors": [
        {
            "color": "black",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [255,255,255,1],
                "hex": "#000"
            }
        },
        {
            "color": "white",
            "category": "value",
            "code": {
                "rgba": [0,0,0,1],
                "hex": "#FFF"
            }
        },
        {
            "color": "red",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [255,0,0,1],
                "hex": "#FF0"
            }
        },
        {
            "color": "blue",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [0,0,255,1],
                "hex": "#00F"
            }
        },
        {
            "color": "yellow",
            "category": "hue",
            "type": "primary",
            "code": {
                "rgba": [255,255,0,1],
                "hex": "#FF0"
            }
        },
        {
            "color": "green",
            "category": "hue",
            "type": "secondary",
            "code": {
                "rgba": [0,255,0,1],
                "hex": "#0F0"
            }
        }
    ]
}
  • Copy this JSON structure in a file and save it as Ex1.json
  • Create an assets folder in the android studio by:-
    • Change Package from Android.
    • Right click on app> select new folder>assets>Click on Finish.
  • Copy the ex1.json file and paste it in the assets folder.

Android Studio Coding Json

In this JSON file, we have a list of colors where each object contains information like color, category, type and different types of code like rgba and hex.  We will use LinearLayoutManager with a vertical orientation to display the array items.

Firstly, we declare a RecyclerView in our XML file and then get the reference of it in our Activity. After that, we fetch the JSON file then parse the JSONArray data and finally set the Adapter to show the items in RecyclerView. Whenever a user clicks on an item the color name is displayed on the screen with the help of Toast.

MUST READ: Google Map Tutorial in Android Studio [Step by Step]

STEPS TO PARSE JSON:-

  • Create a new Activity
  • Open gradle>build.gradle(module:app)

Add dependencies for recycler view and card view:-

implementation "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView
implementation 'com.android.support:cardview-v7:23.0.1' // dependency file for CardView

Activity_main.xml 

In this step, we create a RecyclerView in our XML file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Create another XML file named “list_view.xml”

List_view.xml

To show the data, create textview in list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardMaxElevation="1dp"
    card_view:cardElevation="1dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
       >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/color"
            android:textSize="40dp"
            android:background="@color/colorAccent"
            android:textColor="#ffffff"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/category"
            android:textSize="20dp"
            android:background="@color/cardview_light_background"
            android:textColor="#000000"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/hex"
            android:textSize="20dp"
            android:background="@color/cardview_light_background"
            android:textColor="#000000"/>


    </LinearLayout>

</android.support.v7.widget.CardView>

MainActivity.java

In this step firstly we get the reference of RecyclerView. After that, we fetch the JSON file from assets and parse the JSON data using JSONArray and JSONObject methods and then set a LayoutManager and finally, we set the Adapter to show the items in RecyclerView.

6.	package com.example.json1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> color = new ArrayList<>();
    ArrayList<String> category = new ArrayList<>();
    ArrayList<String> hex = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get the reference of RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        // set a LinearLayoutManager with default vertical orientation
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);

        try {
            // get JSONObject from JSON file
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            // fetch JSONArray named colors
            JSONArray userArray = obj.getJSONArray("colors");
            // implement a loop to get colors list data
            for (int i = 0; i < userArray.length(); i++) {
                // create a JSONObject for fetching single color data
                JSONObject userDetail = userArray.getJSONObject(i);
                // fetch color name and category and store it in arraylist
                color.add(userDetail.getString("color"));
                category.add(userDetail.getString("category"));
                // create an object for getting code data from JSONObject
                JSONObject contact = userDetail.getJSONObject("code");
                // fetch hex value and store it in arraylist
                hex.add(contact.getString("hex"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //  call the constructor of CustomAdapter to send the reference and data to Adapter
        Custom_adapter customAdapter = new Custom_adapter(MainActivity.this, color, category, hex);
        recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
    }


    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("ex1.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

}

Create another java file named Custom_adapter.java

Custom_adapter.java

In this step, we create a CustomAdapter class and extends RecyclerView.Adapter class with ViewHolder in it. After that we implement the overridden methods and create a constructor for getting the data from Activity, In this custom Adapter two methods are more important first is onCreateViewHolder in which we inflate the layout item XML and pass it to View Holder and other is onBindViewHolder in which we set the data in the view’s with the help of ViewHolder.

package com.example.json1;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class Custom_adapter extends RecyclerView.Adapter<Custom_adapter.MyViewHolder>
{
    ArrayList<String> color;
    ArrayList<String> category;
    ArrayList<String> hex;
    Context context;



    public Custom_adapter(Context context, ArrayList<String>color, ArrayList<String> category, ArrayList<String> hex) {
        this.context=context;
        this.color=color;
        this.category=category;
        this.hex=hex;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // infalte the item Layout
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
        MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
        return vh;

    }

    @Override
    public void onBindViewHolder(Custom_adapter.MyViewHolder holder, final int position) {
        // set the data in items
        holder.color.setText(color.get(position));
        holder.category.setText(category.get(position));
        holder.hex.setText(hex.get(position));
        // implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // display a toast with color name on item click
                Toast.makeText(context, color.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return color.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView color, category, hex;// init the item view's

        public MyViewHolder(View itemView) {
            super(itemView);

            // get the reference of item view's
            color = (TextView) itemView.findViewById(R.id.color);
            category = (TextView) itemView.findViewById(R.id.category);
            hex = (TextView) itemView.findViewById(R.id.hex);

        }
    }

}

Congratulations… You have successfully built this Application.

When you will run your application, you can see your interface mentioned as below:-

To access code, click on below GitHub link:-

GITHUB

This was a simple tutorial, JSON Parsing in Android Application using Recycler View and Card View.

Hope, you liked this article. For, more such article… stay tuned!!!! For any Query, comment down below.

Related Stories