JSON Parsing in Android using Android Studio

Usually, most of the application require interchanging of data from the server. During interchanging data, well formatted and structured data is required. JSON parsing is good and well structured, lightweight and easy to parse and human readable. In this tutorial, we will focus how to parse to JSON in Android Studio.JSON parsing
We are going to use very simple JSON in this tutorial, which contains list of students while each node have id,name,gender and phone attributes of a student.

{
"studentinfo": [

{
“id”: “S99”,
“sname”: “Adam Jam” ,
“semail”: “adam.jam@abc.com”,
“address”: “House #33, ABC Lane, ABC CITY 06987”,
“gender” : “male”,
“phone”: {
“mobile”: “+1 1234997890”,
“home”: “00 123456”,
“office”: “00 321654”
}
},
{
“id”: “S101”,
“sname”: “Archbould Tom”,
“semail”: “archbould.tom@axy.com”,
“address”: “House #33, ABC Lane, ABC CITY 06987”,
“gender” : “male”,
“phone”: {
“mobile”: “+1 1234599890”,
“home”: “00 123456”,
“office”: “00 321654”
}
}
]
}

You can download the complete source code of this tutorial here.

Usually, JSON contains two types of nodes, JSONArray and JSONObject. So while parsing the JSON node we have to use the appropriate method. If JSON starts from [ represent JSONArray and if starts from { represent JSONObject.

So if JSON starting from [, we use the getJSONArray method to parse. and same as if JSON start with { we should use the getJSONObject method.

json_parsing_mobilesiri

Create new android project

Start Android Studio and create a new Android project.

We are getting JSON from the internet by making an HTTP call so we need to add internet permission in the project.

Manifest file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobilesiri.jsonparsing" >
<!-- Internet permission -->
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”.MainActivity”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>

Handling HTTP calls

We will use separate class for making the HTTP calls, which can use both GET and POST method for HTTP calls and also could send parameters.
So create a WebRequest.JAVA class and add the following code. makeWebServiceCall(String urladdress, int requestmethod, HashMap<String, String> params) should be called in order to make HTTP calls, whose parameter are
urladdress – URL which is to be called
requestmethod – HTTP request method either GET or POST
params – (Optional) if need to send any parameter with request


package com.mobilesiri.jsonparsing;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class WebRequest {
static String response = null;
public final static int GETRequest = 1;
public final static int POSTRequest = 2;

Read More:  5 Most Common Android Animations' Code

//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* @url – url to make web request
* @requestmethod – http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making web service call
*
* @url – url to make web request
* @requestmethod – http request method
* @params – http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = “”;
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POSTRequest) {
conn.setRequestMethod(“POST”);
} else if (requestmethod == GETRequest) {
conn.setRequestMethod(“GETRequest”);
}

if (params != null) {
OutputStream ostream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(ostream, “UTF-8”));
StringBuilder requestresult = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
requestresult.append(“&”);
requestresult.append(URLEncoder.encode(entry.getKey(), “UTF-8”));
requestresult.append(“=”);
requestresult.append(URLEncoder.encode(entry.getValue(), “UTF-8”));
}
writer.write(requestresult.toString());

writer.flush();
writer.close();
ostream.close();
}
int reqresponseCode = conn.getResponseCode();

if (reqresponseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = “”;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}

We will use listview to show parsed data, so add list view in your MainActivity layout file. As our MainActivity will be ListActivit so keep list view id @android:id/list for the main list.
activity_main.xml


<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">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

We need a layout for listview row. Add a layout in your layout folder with name activity_main.xml and add follow XML.

<?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">
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<!-- Email label -->
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip" />
<!-- Mobile number label -->
<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: " />
</LinearLayout>

Now, in MainActivity declare all JSON nodes and get list view reference.

public class MainActivity extends ListActivity {
// URL to get contacts JSON
private static String url = "https://raw.githubusercontent.com/mobilesiri/JSON-Parsing-in-Android/master/index.html";

// JSON Node names
private static final String TAG_STUDENT_INFO = “studentsinfo”;
private static final String TAG_ID = “id”;
private static final String TAG_STUDENT_NAME = “sname”;
private static final String TAG_STUDENTEMAIL = “semail”;
private static final String TAG_ADDRESS = “address”;
private static final String TAG_STUDENT_GENDER = “gender”;
private static final String TAG_STUDENT_PHONE = “sphone”;
private static final String TAG_STUDENT_PHONE_MOBILE = “mobile”;
private static final String TAG_STUDENT_PHONE_HOME = “home”;

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

// Calling async task to get json
new GetStudents().execute();
}
}

Read More:  Android SQLite Database Tutorial using Android Studio

Read More:Android custom listview tutorial using volley – Android Studio
Read More: Android SQLite Database Tutorial using – Android Studio

JSON Parsing

I add a method ParseJSON which is taking JSON as parameter and retuning HashMap ArrayList of data. Note getJSONArray() or getJSONObject() depend on JSON nodes.

private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);

// Getting JSON Array node
JSONArray students = jsonObj.getJSONArray(TAG_STUDENT_INFO);

// looping through All Students
for (int i = 0; i < students.length(); i++) {
JSONObject c = students.getJSONObject(i);

String id = c.getString(TAG_ID);
String sname = c.getString(TAG_STUDENT_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_STUDENT_GENDER);

// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_STUDENT_PHONE);
String mobile = phone.getString(TAG_STUDENT_PHONE_MOBILE);
String home = phone.getString(TAG_STUDENT_PHONE_HOME);

// tmp hashmap for single student
HashMap<String, String> student = new HashMap<String, String>();

// adding every child node to HashMap key => value
student.put(TAG_ID, id);
student.put(TAG_STUDENT_NAME, sname);
student.put(TAG_EMAIL, email);
student.put(TAG_STUDENT_PHONE_MOBILE, mobile);

// adding student to students list
studentList.add(student);
}
return studentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e(“ServiceHandler”, “No data received from HTTP request”);
return null;
}
}

For making HTTP call to get JSON, we need to add Async class to make HTTP call in the background.
In onPreExecute method, we add a Dialog before calling the URL
In doInBackground, we call method makeWebServiceCall to get JSON and ParseJSON to parse data.
In onPostExecute I dismiss dialog, and create a list Adapter and set to ListView.


private class GetStudents extends AsyncTask<Void, Void, Void> {

// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList;
ProgressDialog proDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(MainActivity.this);
proDialog.setMessage(“Please wait…”);
proDialog.setCancelable(false);
proDialog.show();
}

@Override
protected Void doInBackground(Void… arg0) {
// Creating service handler class instance
WebRequest webreq = new WebRequest();

// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GETRequest);

Log.d(“Response: “, “> ” + jsonStr);

studentList = ParseJSON(jsonStr);

return null;
}

@Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, studentList,
R.layout.list_item, new String[]{TAG_STUDENT_NAME, TAG_EMAIL,
TAG_STUDENT_PHONE_MOBILE}, new int[]{R.id.name,
R.id.email, R.id.mobile});

setListAdapter(adapter);
}

}

Now run the code you will find the data is populated in ListView

Complete MainActivity


package com.mobilesiri.jsonparsing;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

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

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

public class MainActivity extends ListActivity {

Read More:  Android OkHttp Tutorial

// URL to get contacts JSON
private static String url = “https://raw.githubusercontent.com/BilCode/AndroidJSONParsing/master/index.html”;

// JSON Node names
private static final String TAG_STUDENT_INFO = “studentsinfo”;
private static final String TAG_ID = “id”;
private static final String TAG_STUDENT_NAME = “sname”;
private static final String TAG_STUDENTEMAIL = “semail”;
private static final String TAG_ADDRESS = “address”;
private static final String TAG_STUDENT_GENDER = “gender”;
private static final String TAG_STUDENT_PHONE = “sphone”;
private static final String TAG_STUDENT_PHONE_MOBILE = “mobile”;
private static final String TAG_STUDENT_PHONE_HOME = “home”;

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

// Calling async task to get json
new GetStudents().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetStudents extends AsyncTask<Void, Void, Void> {

// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList;
ProgressDialog proDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(MainActivity.this);
proDialog.setMessage(“Please wait…”);
proDialog.setCancelable(false);
proDialog.show();
}
@Override
protected Void doInBackground(Void… arg0) {
// Creating service handler class instance
WebRequest webreq = new WebRequest();

// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GETRequest);

Log.d(“Response: “, “> ” + jsonStr);

studentList = ParseJSON(jsonStr);

return null;
}
@Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, studentList,
R.layout.list_item, new String[]{TAG_STUDENT_NAME, TAG_EMAIL,
TAG_STUDENT_PHONE_MOBILE}, new int[]{R.id.name,
R.id.email, R.id.mobile});

setListAdapter(adapter);
}

}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();

JSONObject jsonObj = new JSONObject(json);

// Getting JSON Array node
JSONArray students = jsonObj.getJSONArray(TAG_STUDENT_INFO);

// looping through All Students
for (int i = 0; i < students.length(); i++) {
JSONObject c = students.getJSONObject(i);

String id = c.getString(TAG_ID);
String name = c.getString(TAG_STUDENT_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_STUDENT_GENDER);

// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_STUDENT_PHONE);
String mobile = phone.getString(TAG_STUDENT_PHONE_MOBILE);
String home = phone.getString(TAG_STUDENT_PHONE_HOME);

// tmp hashmap for single student
HashMap<String, String> student = new HashMap<String, String>();

// adding every child node to HashMap key => value
student.put(TAG_ID, id);
student.put(TAG_STUDENT_NAME, name);
student.put(TAG_EMAIL, email);
student.put(TAG_STUDENT_PHONE_MOBILE, mobile);

// adding student to students list
studentList.add(student);
}
return studentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e(“ServiceHandler”, “No data received from HTTP Request”);
return null;
}
}
}

You can download the complete source code of this tutorial here.

Output:

mobilesiri-listview-jsonparser

MobileSiri.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. Read about our Affiliates Disclosure Policy here.