Android JSON Parsing Tutorial

Thumb-Android-JSON-Parsing-Tutorial

17th February, 2020

Hi Android developer!

JSON (JavaScript Object Notation) is readable format for structuring data. It is used to transmit data between a server and web application. If you want to get data from a JSON file. First you have to parse JSON data then you can use that data to display. In this example you will learn how to parse JSON data from assets folder.

Android JSON Parsing without Any Library

JSON Data Structure
JSON Data Structure

Step 1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 2: Create Assets Folder

Create a assets folder inside main directory and put your JSON file inside it.

assets folder in the android studio
Assets folder in the Android Studio

Project ⇒ app ⇒ src ⇒ main ⇒ assets⇒ employee_data.json

{
  "employee":
  [
    {
      "name": "Ava",
      "gender": "Female",
      "age": 26
    },
    {
      "name": "Daniel",
      "gender": "Male",
      "age": 35
    },
    {
      "name": "Emily",
      "gender": "Female",
      "age": 32
    }
  ]
}

Step 3: Load JSON Data From Assets Folder

To load JSON data from assets folder, open the Activity and add the code below.

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

Step 4: Display JSON Data in the RecyclerView

4.1: Add RecyclerView dependencies to the App Level Gradle.

Project ⇒ app ⇒ build.gradle

dependencies {
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
}

4.2: Add the RecyclerView to the Activity Layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    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=".MainActivity">
    
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

4.3: Create a model class that represents employees details.

package com.codestringz.jsontest;

public class Employee
{
    private String name;
    private String gender;
    private int age;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getGender()
    {
        return gender;
    }

    public void setGender(String gender)
    {
        this.gender = gender;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

4.4: Create a layout resource file. This layout will used to display employees details in the RecyclerView.

<?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:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name" />

    <TextView
        android:id="@+id/textViewGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Gender" />

    <TextView
        android:id="@+id/textViewAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Age" />
</LinearLayout>

4.5: Create a Adapter for the RecyclerView.

package com.codestringz.jsontest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder>
{
    private ArrayList<Employee> mList = new ArrayList<>();

    public MyRecyclerViewAdapter(ArrayList<Employee> mList)
    {
        this.mList = mList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_row, parent, false);

        MyViewHolder myViewHolder = new MyViewHolder(view);

        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position)
    {
        String name = "Name: " + mList.get(position).getName();
        holder.nameTextView.setText(name);

        String gender = "Gender: " + mList.get(position).getGender();
        holder.genderTextView.setText(gender);

        String age = "Age: " + mList.get(position).getAge();
        holder.ageTextView.setText(age);
    }

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

    @Override
    public int getItemViewType(int position)
    {
        return position;
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {
        private TextView nameTextView;
        private TextView genderTextView;
        private TextView ageTextView;

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

            nameTextView = view.findViewById(R.id.textViewName);
            genderTextView = view.findViewById(R.id.textViewGender);
            ageTextView = view.findViewById(R.id.textViewAge);
        }
    }
}

4.6: Now modify the Activity. Load JSON Data from the assets folder. Create an object of the RecyclerView Adapter and set it to the RecyclerView.

IMG-JSON-Data-Parsing-in-Android
JSON Parsing in Android
package com.codestringz.jsontest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

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

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
{
    private ArrayList<Employee> mEmployeesList = new ArrayList<>();

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

        getEmployeeList();
        setUIRef();
    }

    private void setUIRef()
    {
        RecyclerView recyclerView = findViewById(R.id.myRecyclerView);

        MyRecyclerViewAdapter myRecyclerViewAdapter = new MyRecyclerViewAdapter(mEmployeesList);

        recyclerView.setAdapter(myRecyclerViewAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
    }

    private void getEmployeeList()
    {
        String myJSONStr = loadJSONFromAsset("employee_data.json");

        try
        {
            //Get root JSON object node
            JSONObject rootJSONObject = new JSONObject(myJSONStr);

            //Get employee array node
            JSONArray employeeJSONArray = rootJSONObject.getJSONArray("employee");

            for (int i = 0; i < employeeJSONArray.length(); i++)
            {
                //Create a temp object of the employee model class
                Employee aEmployee = new Employee();

                //Get employee JSON object node
                JSONObject jsonObject = employeeJSONArray.getJSONObject(i);

                //Get employee details
                aEmployee.setName(jsonObject.getString("name"));
                aEmployee.setGender(jsonObject.getString("gender"));
                aEmployee.setAge(jsonObject.getInt("age"));

                //Add employee object to the list
                mEmployeesList.add(aEmployee);
            }

        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    public String loadJSONFromAsset(String fileName)
    {
        String json;
        try
        {
            InputStream is = getAssets().open(fileName);
            int size = is.available();
            byte[] buffer = new byte[size];
            //noinspection ResultOfMethodCallIgnored
            is.read(buffer);
            is.close();
            json = new String(buffer, StandardCharsets.UTF_8);
        } catch (IOException ex)
        {
            ex.printStackTrace();
            return null;
        }
        return json;
    }
}
Display JSON Data In the RecyclerView
JSON Data in the RecyclerView

Watch Video Tutorial

Android JSON Parsing using Google GSON Library

GSON is an open-source library that is used to convert java objects to JSON and vice-versa. Let’s see how to convert existing employee JSON data to java objects.

Step 1: Add GSON Library Dependencies

Add GSON Library dependencies to the app level gradle.

Project ⇒ app ⇒ build.gradle

dependencies {
    implementation 'com.google.code.gson:gson:2.8.6'
}

Step 2: Prepare Model classes

Create model classes that correspond to the structure of JSON data.

package com.codestringz.jsontest;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

public class EmployeeData
{
    @SerializedName("employee")
    private ArrayList<Employee> employees = new ArrayList<>();

    public ArrayList<Employee> getEmployees()
    {
        return employees;
    }

    public void setEmployees(ArrayList<Employee> employees)
    {
        this.employees = employees;
    }
}

Modify existing Employee model class with the code below.

package com.codestringz.jsontest;

import com.google.gson.annotations.SerializedName;

public class Employee
{
    @SerializedName("name")
    private String name;
    
    @SerializedName("gender")
    private String gender;
    
    @SerializedName("age")
    private int age;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getGender()
    {
        return gender;
    }

    public void setGender(String gender)
    {
        this.gender = gender;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

Step 3: Update Activity

Open the Activity and get the JSON data using GSON Library.

package com.codestringz.jsontest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.res.AssetManager;
import android.os.Bundle;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
{
    private EmployeeData mEmployeeData;

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

        getEmployeeList();
        setUIRef();
    }
    private void setUIRef()
    {
        RecyclerView recyclerView = findViewById(R.id.myRecyclerView);

        MyRecyclerViewAdapter myRecyclerViewAdapter = new MyRecyclerViewAdapter(mEmployeeData.getEmployees());

        recyclerView.setAdapter(myRecyclerViewAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
    }

    private void getEmployeeList()
    {
        AssetManager assetManager = getAssets();
        try
        {
            InputStream inputStream = assetManager.open("employee_data.json");

            Gson gson = new Gson();

            Reader reader = new InputStreamReader(inputStream);

            mEmployeeData = gson.fromJson(reader, EmployeeData.class);
            
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Watch Video Tutorial

Happy coding!

Leave a Reply