JSON Parsing in Android Studio

Introduction

 
Two types of parsing are available in android; JSON parsing and XML parsing. JSON is the acronym for JavaScript Object Notation. JSON, as well as XML, are basically for storing data in files. It is said often that JSON is the best alternative to XML for storing data in files. It is easy to parse and access data stored in JSON format. For retrieving the data stored in JSON or XML files, parsing is to be performed on these files.
 
In today's article, you will learn JSON Parsing. We will parse data present in JSON format and view it in the form of a List.
 
The JSON data being used is (taken from http://docs.blackberry.com/sampledata.json ):
  1. [  
  2.     {  
  3.         "vehicleType": "excavator",  
  4.         "vehicleColor": "yellow",  
  5.         "fuel": "diesel",  
  6.         "approvedOperators":  
  7.         [  
  8.             {  
  9.                 "name": "Greg Stark",  
  10.                 "experiencePoints": 13  
  11.             },  
  12.             {  
  13.                 "name": "Aarti Patel",  
  14.                 "experiencePoints": 21  
  15.             },  
  16.             {  
  17.                 "name": "Tarek Mizan",  
  18.                 "experiencePoints": 9  
  19.             }  
  20.         ],  
  21.         "treadType": "plate chain"  
  22.     },  
  23.     {  
  24.         "vehicleType": "Dump Truck",  
  25.         "vehicleColor": "yellow",  
  26.         "fuel": "gasoline",  
  27.         "approvedOperators":  
  28.         [  
  29.             {  
  30.                 "name": "Marc Gervais",  
  31.                 "experiencePoints": 8  
  32.             },  
  33.             {  
  34.                 "name": "Atsuko Iwamoto",  
  35.                 "experiencePoints": 3  
  36.             },  
  37.             {  
  38.                 "name": "Chadwick Price",  
  39.                 "experiencePoints": 54  
  40.             }  
  41.         ],  
  42.         "treadType": "wheel"  
  43.     },  
  44.     {  
  45.         "vehicleType": "Grader",  
  46.         "vehicleColor": "green",  
  47.         "fuel": "diesel",  
  48.         "approvedOperators":  
  49.         [  
  50.             {  
  51.                 "name": "Arun Verma",  
  52.                 "experiencePoints": 34  
  53.             },  
  54.             {  
  55.                 "name": "Morgan Parker",  
  56.                 "experiencePoints": 56  
  57.             },  
  58.             {  
  59.                 "name": "Paul Turner",  
  60.                 "experiencePoints": 17  
  61.             }  
  62.         ],  
  63.         "treadType": "wheel"  
  64.     }  

Step 1
 
Open "activity_main" and append the following code to it:
  1. <ListView  
  2.             android:id="@android:id/list"  
  3.             android:layout_width="fill_parent"  
  4.             android:layout_height="wrap_content"/> 
The layout looks like:
 
im1.jpg
 
Step 2
 
To create a view inside the ListView, create a new layout file. Right-click on "Layout" -> "New" -> "Layout resource file". Name it "list_activity" and add the following code to it:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.    
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  4.               android:orientation="vertical"  
  5.               android:layout_width="match_parent"  
  6.               android:layout_height="match_parent">  
  7.   <LinearLayout  
  8.           xmlns:android="http://schemas.android.com/apk/res/android"  
  9.           android:layout_width="fill_parent"  
  10.           android:layout_height="wrap_content"  
  11.           android:orientation="vertical">  
  12.    
  13.     <TextView  
  14.             android:id="@+id/vehicleType"  
  15.             android:layout_width="fill_parent"  
  16.             android:layout_height="wrap_content"  
  17.             android:textSize="16sp"  
  18.             android:textStyle="bold"  
  19.             android:paddingTop="6dip"  
  20.             android:paddingBottom="2dip" />  
  21.    
  22.     <TextView  
  23.             android:id="@+id/vehicleColor"  
  24.             android:layout_width="fill_parent"  
  25.             android:layout_height="wrap_content"  
  26.             android:paddingBottom="2dip">  
  27.     </TextView>  
  28.    
  29.     <LinearLayout  
  30.             android:layout_width="fill_parent"  
  31.             android:layout_height="wrap_content"  
  32.             android:orientation="horizontal">  
  33.    
  34.       <TextView  
  35.               android:id="@+id/fuel"  
  36.               android:layout_width="wrap_content"  
  37.               android:layout_height="wrap_content"  
  38.               android:gravity="left"  
  39.               android:textStyle="bold"  
  40.               android:text="Mobile: " >  
  41.       </TextView>  
  42.    
  43.     </LinearLayout>  
  44.   </LinearLayout>  
  45.    
  46. </LinearLayout> 
Step 3
 
Open  "MainActivity" and make the following changes:
  1. package com.chhavi.jasonnew;  
  2.    
  3. import android.app.ListActivity;  
  4. import android.app.ProgressDialog;  
  5. import android.content.Context;  
  6. import android.os.AsyncTask;  
  7. import android.os.Bundle;  
  8. import android.app.Activity;  
  9. import android.util.Log;  
  10. import android.view.Menu;  
  11. import android.widget.ListAdapter;  
  12. import android.widget.ListView;  
  13. import android.widget.SimpleAdapter;  
  14.    
  15. import org.json.JSONArray;  
  16. import org.json.JSONException;  
  17. import org.json.JSONObject;  
  18.    
  19. import java.util.ArrayList;  
  20. import java.util.HashMap;  
  21.    
  22. public class MainActivity extends ListActivity {  
  23.    
  24.     private Context context;  
  25.     private static String url = "http://docs.blackberry.com/sampledata.json";  
  26.    
  27.     private static final String type = "vehicleType";  
  28.     private static final String color = "vehicleColor";  
  29.     private static final String fuel = "fuel";  
  30.    
  31.     ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();  
  32.    
  33.     ListView lv ;  
  34.    
  35.     @Override  
  36.     protected void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.activity_main);  
  39.         new ProgressTask(MainActivity.this).execute();  
  40.     }  
  41.    
  42.    
  43.     private class ProgressTask extends AsyncTask<String, Void, Boolean> {  
  44.         private ProgressDialog dialog;  
  45.    
  46.         public ProgressTask(ListActivity activity) {  
  47.    
  48.             Log.i("1""Called");  
  49.             context = activity;  
  50.             dialog = new ProgressDialog(context);  
  51.         }  
  52.    
  53.         private Context context;  
  54.    
  55.         protected void onPreExecute() {  
  56.             this.dialog.setMessage("Progress start");  
  57.             this.dialog.show();  
  58.         }  
  59.    
  60.         @Override  
  61.         protected void onPostExecute(final Boolean success) {  
  62.             if (dialog.isShowing()) {  
  63.                 dialog.dismiss();  
  64.             }  
  65.             ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_item, new String[] { type, color, fuel }, new int[] { R.id.vehicleType, R.id.vehicleColor, R.id.fuel });  
  66.             setListAdapter(adapter);  
  67.             lv = getListView();  
  68.    
  69.         }  
  70.    
  71.         protected Boolean doInBackground(final String... args) {  
  72.    
  73.             JSONParser jParser = new JSONParser();  
  74.             JSONArray json = jParser.getJSONFromUrl(url);  
  75.    
  76.             for (int i = 0; i < json.length(); i++) {  
  77.    
  78.                 try {  
  79.                     JSONObject c = json.getJSONObject(i);  
  80.                     String vtype = c.getString(type);  
  81.    
  82.                     String vcolor = c.getString(color);  
  83.                     String vfuel = c.getString(fuel);  
  84.                     
  85.                     HashMap<String, String> map = new HashMap<String, String>();  
  86.    
  87.                     map.put(type, vtype);  
  88.                     map.put(color, vcolor);  
  89.                     map.put(fuel, vfuel);  
  90.    
  91.    
  92.                     jsonlist.add(map);  
  93.                 } catch (JSONException e)  
  94.                 {  
  95.                             e.printStackTrace();  
  96.                 }  
  97.             }  
  98.             return null;  
  99.    
  100.         }  
  101.    
  102.     }  
  103.    
  104.     @Override  
  105.     public boolean onCreateOptionsMenu(Menu menu) {  
  106.         // Inflate the menu; this adds items to the action bar if it is present.  
  107.         getMenuInflater().inflate(R.menu.main, menu);  
  108.         return true;  
  109.     }  
  110.    

Note the use of the JSON URL above.
 
Step 4
 
Now let us create a JSONParser class that is used above. Right-click on the same package then select "New" -> "Java class". Name this file "JSONParser" and add the following code to it:
  1. package com.chhavi.jasonnew;  
  2.    
  3. import android.util.Log;  
  4.    
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.StatusLine;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.impl.client.DefaultHttpClient;  
  12. import org.json.JSONArray;  
  13. import org.json.JSONException;  
  14.    
  15. import java.io.BufferedReader;  
  16. import java.io.IOException;  
  17. import java.io.InputStream;  
  18. import java.io.InputStreamReader;  
  19.    
  20. public class JSONParser {  
  21.    
  22.     static InputStream is = null;  
  23.     static JSONArray jarray = null;  
  24.     static String json = "";  
  25.    
  26.     public JSONParser() {  
  27.     }  
  28.    
  29.     public JSONArray getJSONFromUrl(String url) {  
  30.    
  31.         StringBuilder builder = new StringBuilder();  
  32.         HttpClient client = new DefaultHttpClient();  
  33.         HttpGet httpGet = new HttpGet(url);  
  34.         try {  
  35.             HttpResponse response = client.execute(httpGet);  
  36.             StatusLine statusLine = response.getStatusLine();  
  37.             int statusCode = statusLine.getStatusCode();  
  38.             if (statusCode == 200) {  
  39.                 HttpEntity entity = response.getEntity();  
  40.                 InputStream content = entity.getContent();  
  41.                 BufferedReader reader = new BufferedReader(new InputStreamReader(content));  
  42.                 String line;  
  43.                 while ((line = reader.readLine()) != null) {  
  44.                     builder.append(line);  
  45.                 }  
  46.             } else {  
  47.                 Log.e("Error....""Failed to download file");  
  48.             }  
  49.         } catch (ClientProtocolException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.    
  55.         try {  
  56.             jarray = new JSONArray( builder.toString());  
  57.         } catch (JSONException e) {  
  58.             Log.e("JSON Parser""Error parsing data " + e.toString());  
  59.         }  
  60.    
  61.           return jarray;  
  62.    
  63.     }  

JSONArray class: a dense indexed sequence of values. Instances of this class are not thread-safe. This is a non-final class.
 
In this class, the JSON file is parsed and a JSON array is being returned. This returned array is then used to display the data in the form of a List using "MainActivity".
 
Step 5
 
Do not forget to add the internet permission in "AndroidManifest.xml" as in the following:
  1. <uses-permission android:name="android.permission.INTERNET"/>  
This permission is to be added before the <uses-sdk> tag in "AndroidManifest".
 
The output snapshots:
 
im2.jpg
 
im3f.jpg
 
Thank you... Enjoy coding :)


Similar Articles