JSON Parsing in Android – Step by Step Implementation

In this DataFlair Android tutorial, we’re going to cover the JSON parsing in Android. Before getting into that, first, know what JSON is.

JSON stands for JavaScript Object Notation. It is a format for data exchange and storage. When compared to XML, it is very simple and easy to parse information interchange format. JSON is extensively used for data exchange between the device and server in android applications. In this tutorial, we’ll implement JSON parsing with a simple example.

When we talk about JSON, it is a lightweight data-interchange format that is language independent. Though it uses the syntax of JavaScript, it is limited to text.

JSON Parsing in android

Do you want to become an Android Professional? Join Android Telegram Channel

JSON Structures in Android

JSON uses two types of brackets that are as follows:

  • [] – To declare the elements of Array in JSON, they’re written in square brackets.
  • {} – To create JSON objects, the elements are written in curly brackets.

JSON has the following types of structures that are:

1. JSON Objects

The elements inside the curly brackets are known as Objects.

2. JSON Array

A list of values, known as Arrays.

3. JSON Key-Value

This data is stored as a pair of keys and values. Here the keys can be a name, a number for which the values can be Seema, 98767586 etc.

Why JSON Parsing in Android over XML?

Let us see some reasons for why to choose JSON over XML:

  • It is much easier and quicker with high performance
  • It can use arrays
  • Its libraries do not depend on other libraries
  • The codes written in JSON are short, clean and easy to understand
  • It is free to open use and open-source tool
  • In JSON value retrieval is easy
  • It has a fully automated way of serializing/deserializing JavaScript.
  • It is supported by many Ajax toolkits and most of the backend technologies.

Examples of XML and JSON

Let us see the code difference of JSON and XML files:

XML Example:

<?xml version= “1.0” encoding= “” ?>
<student>
        <student>
  <name> Sia Sharma</name>
  <city> Chandigarh</city>
 	      </student>
        <student>
  <name>Dimple D’souza</name>
  <city> Nagpur</city>
 	      </student>
      <student>
  <name>Anna Jones</name>
  <city> Mumbai</city>
 	      </student>

  </student>

JSON Example:

{ “students”: [
{ “name”: “Sia Sharma”, “city”: “Chandigarh”},
{ “name”: “Prachi D’Souza”, “city”: “Nagpur”},
{ “name”: “Annas Jones”, “city”: “Mumbai”}
]}

I hope the difference is all clear in front of you. This is how simple JSON is and how easily it could be understood.

JSON Parsing Functions in Android

Here are functions which we need for JSON parsing:

1. get(int index)

This function gets the value of the object type present in the JSON array.

2. getType(int index)

Here Type can be Int, Double, Boolean, Long, String, JSONArray, or JSONObject. This function gets the value of any of the mentioned types present in the JSON array.

3. length()

using this function, we get the length of the array that has come from the server.

4. opt(int index)

This function returns the Object Type value in the JSONArray at a particular index.

5. optType(int index )

Here Type can be Int, Double, Boolean, Long, String, JSONArray, or JSONObject. This function returns the value of the mentioned types in the JSONArray at a particular index.

JSON Implementation in Android

Now we’ll implement it using the following steps;

1. First of all, we will create a new project and name it
2. Then write the following in the activity_main.xml file:

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

   <TextView
       android:id="@+id/textView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerHorizontal="true"
       android:layout_marginLeft="90dp"
       android:layout_marginTop="30dp"
       android:text="DataFlair "
       android:textColor="#00574B"
       android:textSize="50dp"
       android:textStyle="bold" />

   <ListView
       android:id="@+id/students"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:dividerHeight="1dp" />
</LinearLayout>

3. Next, create a new layout and name it as list.xml. And write the following code in it:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:padding="5dip">

   <TextView
       android:id="@+id/StudentName"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textColor="#024E46"
       android:textSize="25dp"
       android:textStyle="bold" />

   <TextView
       android:id="@+id/Branch"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@id/StudentName"
       android:layout_marginTop="10dp"
       android:textColor="#A5BAB8"
       android:textSize="20dp" />

   <TextView
       android:id="@+id/institute"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentRight="true"
       android:textColor="#A5BAB8"
       android:textSize="20dp" />
</RelativeLayout>

4. Now write the following code in the MainActivity.java file:

package com.dataflair.myjsonparsing;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.appcompat.app.AppCompatActivity;

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

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       String json_stu = getListData();
       try {
           ArrayList<HashMap<String, String>> userList = new ArrayList<>();
           ListView listview = findViewById(R.id.students);
           JSONObject jsObj = new JSONObject(json_stu);
           JSONArray jsArray = jsObj.getJSONArray("Students");
           for (int i = 0; i < jsArray.length(); i++) {
               HashMap<String, String> stu = new HashMap<>();
               JSONObject obj = jsArray.getJSONObject(i);
               stu.put("name", obj.getString("name"));
               stu.put("Branch", obj.getString("Branch"));
               stu.put("institute", obj.getString("institute"));
               userList.add(stu);
           }
           ListAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list, new String[]{"name", "Branch", "institute"}, new int[]{R.id.StudentName, R.id.Branch, R.id.institute});
           listview.setAdapter(simpleAdapter);
       } catch (JSONException ex) {
           Log.e("JsonParser ", "Exception", ex);
       }
   }

   private String getListData() {
       String json_stu1 = "{ \"Students\" :[" +
               "{\"name\":\"Akshita Shrivastava \",\"Branch\":\"Computer Science\",\"institute\":\"IIT I\"}" +
               ",{\"name\":\"Peter Potter\",\"Branch\":\"Civil\",\"institute\":\" IIT R\"}" +
               ",{\"name\":\"Md Farman \",\"Branch\":\"Information Technology\",\"institute\":\" Bits Pilani\"}" +
               ",{\"name\":\"Vipul Soni\",\"Branch\":\"Mechanical\",\"institute\":\" MIT\"}" +
               ",{\"name\":\"Shikha Jain\",\"Branch\":\"Textile\",\"institute\":\" IIIT\"}" +
               ",{\"name\":\"John Samuel\",\"Branch\":\"Electrical\",\"institute\":\" IIT B\"}" +
               ",{\"name\":\"Rhea Sharma\",\"Branch\":\"Mechanical\",\"institute\":\"NIT\"}] }";
       return json_stu1;
   }
}

5. Then we’ll run the app and following would be the output:

Android JSON Parsing

Summary

In this article, we have read about JSON parsing in Android. We have learned what JSON is, what its key features are and why to choose JSON over XML. We also saw the functions for JSON parsing and then we did JSON Parsing in Android step by step implementation as well.

Thank You.

Don’t forget to share your Google rating for DataFlair!!!

2 Responses

  1. Himanshu Sharma says:

    Helpful for my college project

    Thank you

  2. Akshita says:

    Thank You

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.