Android - SPLessons

Android JSON Parser

Chapter 22

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android JSON Parser

Android JSON Parser

Android JavaScript Object Notation (JSON) parser is lightweight, structured, and easy to parse independent data exchange format that allows you to parse data present in the JSON format. It is the best alternative to XML when your app requires to exchange data with your server. Android provides four classes to manipulate JSON data: JSONArray, JSONObject, JSONStringer and JSONTokenizer. In this chapter, you will learn how to use Android JSON Parser to parse the JSON file and extract required information from it.

JSON- Structure and Elements:

AsyncTask is an abstract class which helps the Android applications to handle the Main UI thread. AsyncTask class allows you to perform long running operations(parsing) and shows the result on the UI thread without affecting the main thread.
When an asynchronous task is executed from the UI main thread, it passes through four steps:

This method is invoked before doInBackground method is called on the UI thread. This method is normally used to setup the task like showing progress bar in the UI.
Code/process running for long time should be put in doInBackground method. When execute method is called in the UI main thread, this method is called with the parameters passed.
This method is invoked by calling publishProgress at anytime from doInBackground. This method can be used to display any form of progress in the user interface.
This method is invoked after doInBackground method completes processing. Outcome of the doInBackground is passed to this method.

Cancellation of an AsyncTask:

The AsyncTask can be cancelled by invoking cancel(boolean) method. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns.

Rules to be followed while implementing AsyncTask:
1. The AsyncTask class must be loaded on the UI thread.
2. The task instance must be created on the UI thread.
3. Method execute (Params…) must be invoked on the UI thread.
4. Should not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually.
5. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

The following example illustrates how to parse data using JSONParser and AsyncTask.

First create employee.txt/employee.json in assets folder(if you are using static data)

"employee":[ {
"name": "John B",
"email": "",
"number": "2345678987"
} ,
"name": "Amit",
"email": "",
"number": "2567678987"
} ]
} ;

Now Create under src/<your packagename>/

public class MainActivity extends Activity{

ArrayList nameL=new ArrayList();
ArrayList emailL=new ArrayList();
ArrayList numberL=new ArrayList();
ArrayList idL=new ArrayList();
Context context;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//hide action bar
//set activity to external view

final Button access=(Button)findViewById(;
final TextView text=(TextView)findViewById(;


//on click access
access.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
final JSONParsing jp=new JSONParsing(context);
JSONParsing.h=new Handler()
public void handleMessage(android.os.Message msg) {
JSONObject emp;
try {
//create instance of JSONObject
emp = (new JSONObject(;
//get JSONArray
JSONArray jarray=emp.getJSONArray("employee");
for(int i=0;i<jarray.length();i++)
JSONObject jo=jarray.getJSONObject(i);
 String id=jo.getString("id");
 String name=jo.getString("name");
 String email=jo.getString("email");
 String number=jo.getString("number"); 

//You can use listview to display data
} catch (JSONException e) {
// TODO Auto-generated catch block




Create class

public class JSONParsing extends AsyncTask{
 //variable declaration
 ProgressDialog dialog;
 Context context;
 static Handler h;
 //ProgressDialog dialog;
 String data;
 JSONParsing(Context context)
 protected void onPreExecute() {
 // TODO Auto-generated method stub
 super.onPreExecute();, "Loading", "Please wait");

 protected void onPostExecute(String result) {
 // TODO Auto-generated method stub

 protected String doInBackground(String... params) {
 // TODO Auto-generated method stub

 //create URL
 URL url;
 try {

  /*if you are accessing data from URL use this
 url = new URL("");
 //URL Encoding
 URI uri=new URI(url.getProtocol(),url.getUserInfo(),url.getHost(),url.getPort(),url.getPath(),url.getQuery(),url.getRef());
 //convert URI to URL
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();


 InputStream stream = conn.getInputStream();*/

 InputStream stream = context.getAssets().open("employee.txt");

 data = convertStreamToString(stream);


 } catch (Exception e) {

 return null;
 static String convertStreamToString( is) {
 java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

 return s.hasNext() ? : "";


Create activity_main.xml in res/layout folder


        <Button />



If you are accessing data from the server using HTTP connection add Internet permission to your AndroidManifest.xml file.

 <uses-permission android:name="android.permission.INTERNET"/>