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:
• JSONArray([):A square bracket ([) represents JSON array
• JSONObject({): A curly bracket ({)represents JSON object. Pairs of key/value make up a JSON object.
• Key: A JSON Object contains a key in the string format.
• Value: Each key has a value, which is an object to be accumulated under the key. A value can be a string or number or true or false or null or an object or an array.
In order to parse a JSON object, we should create an object of class JSONObject and specify a string containing JSON data to it.
Ex:
String data;
JSONObject jObj = new JSONObject(data);
A JSON file consists of JSONArray. To get JSONArray use getJSONArray() method.
Ex:
JSONArray jarray= jObj.getJSONArray("employee");
A JSON file also consists of different objects with different key/value pair. So, JSONObject has to be a separate function to parse each of the components of the JSON file.
Ex:
The method getJSONObject returns the JSON object. The method getString returns the string value of the specified key.
In addition to the getString method, there are also other methods such as:
• get(String name): This method just returns the value but in the form of Object type
• getBoolean(String name): This method returns the boolean value specified by the key
• getDouble(String name): This method returns the double value specified by the key
• getInt(String name): This method returns the integer value specified by the key
• getLong(String name): This method returns the long value specified by the key
• length(): This method returns the number of name/value mappings in this object
• names(): This method returns an array containing the string names in this object
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)