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 ):

[

    {

        "vehicleType": "excavator",

        "vehicleColor": "yellow",

        "fuel": "diesel",

        "approvedOperators":

        [

            {

                "name": "Greg Stark",

                "experiencePoints": 13

            },

            {

                "name": "Aarti Patel",

                "experiencePoints": 21

            },

            {

                "name": "Tarek Mizan",

                "experiencePoints": 9

            }

        ],

        "treadType": "plate chain"

    },

    {

        "vehicleType": "Dump Truck",

        "vehicleColor": "yellow",

        "fuel": "gasoline",

        "approvedOperators":

        [

            {

                "name": "Marc Gervais",

                "experiencePoints": 8

            },

            {

                "name": "Atsuko Iwamoto",

                "experiencePoints": 3

            },

            {

                "name": "Chadwick Price",

                "experiencePoints": 54

            }

        ],

        "treadType": "wheel"

    },

    {

        "vehicleType": "Grader",

        "vehicleColor": "green",

        "fuel": "diesel",

        "approvedOperators":

        [

            {

                "name": "Arun Verma",

                "experiencePoints": 34

            },

            {

                "name": "Morgan Parker",

                "experiencePoints": 56

            },

            {

                "name": "Paul Turner",

                "experiencePoints": 17

            }

        ],

        "treadType": "wheel"

    }

]

 

Step 1:

Open "activity_main" and append the following code to it:

<ListView

            android:id="@android:id/list"

            android:layout_width="fill_parent"

            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:

<?xml version="1.0" encoding="utf-8"?>

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:orientation="vertical"

              android:layout_width="match_parent"

              android:layout_height="match_parent">

  <LinearLayout

          xmlns:android="http://schemas.android.com/apk/res/android"

          android:layout_width="fill_parent"

          android:layout_height="wrap_content"

          android:orientation="vertical">

 

    <TextView

            android:id="@+id/vehicleType"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:textSize="16sp"

            android:textStyle="bold"

            android:paddingTop="6dip"

            android:paddingBottom="2dip" />

 

    <TextView

            android:id="@+id/vehicleColor"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:paddingBottom="2dip">

    </TextView>

 

    <LinearLayout

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:orientation="horizontal">

 

      <TextView

              android:id="@+id/fuel"

              android:layout_width="wrap_content"

              android:layout_height="wrap_content"

              android:gravity="left"

              android:textStyle="bold"

              android:text="Mobile: " >

      </TextView>

 

 

 

    </LinearLayout>

  </LinearLayout>

 

</LinearLayout>

 

Step 3:

Open  "MainActivity" and make the following changes:

package com.chhavi.jasonnew;

 

import android.app.ListActivity;

import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;

import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

import android.widget.ListAdapter;

import android.widget.ListView;

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 {

 

    private Context context;

    private static String url = "http://docs.blackberry.com/sampledata.json";

 

    private static final String type = "vehicleType";

    private static final String color = "vehicleColor";

    private static final String fuel = "fuel";

 

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

 

    ListView lv ;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new ProgressTask(MainActivity.this).execute();

    }

 

 

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {

        private ProgressDialog dialog;

 

        public ProgressTask(ListActivity activity) {

 

            Log.i("1", "Called");

            context = activity;

            dialog = new ProgressDialog(context);

        }

 

        private Context context;

 

        protected void onPreExecute() {

            this.dialog.setMessage("Progress start");

            this.dialog.show();

        }

 

        @Override

        protected void onPostExecute(final Boolean success) {

            if (dialog.isShowing()) {

                dialog.dismiss();

            }

            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 });

            setListAdapter(adapter);

            lv = getListView();

 

        }

 

        protected Boolean doInBackground(final String... args) {

 

            JSONParser jParser = new JSONParser();

            JSONArray json = jParser.getJSONFromUrl(url);

 

            for (int i = 0; i < json.length(); i++) {

 

                try {

                    JSONObject c = json.getJSONObject(i);

                    String vtype = c.getString(type);

 

                    String vcolor = c.getString(color);

                    String vfuel = c.getString(fuel);

                  

                    HashMap<String, String> map = new HashMap<String, String>();

 

                    map.put(type, vtype);

                    map.put(color, vcolor);

                    map.put(fuel, vfuel);

 

 

                    jsonlist.add(map);

                } catch (JSONException e)

                {

                            e.printStackTrace();

                }

            }

            return null;

 

        }

 

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

 

}


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:

package com.chhavi.jasonnew;

 

import android.util.Log;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.StatusLine;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

 

public class JSONParser {

 

    static InputStream is = null;

    static JSONArray jarray = null;

    static String json = "";

 

    public JSONParser() {

    }

 

    public JSONArray getJSONFromUrl(String url) {

 

        StringBuilder builder = new StringBuilder();

        HttpClient client = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(url);

        try {

            HttpResponse response = client.execute(httpGet);

            StatusLine statusLine = response.getStatusLine();

            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) {

                HttpEntity entity = response.getEntity();

                InputStream content = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(content));

                String line;

                while ((line = reader.readLine()) != null) {

                    builder.append(line);

                }

            } else {

                Log.e("Error....", "Failed to download file");

            }

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

 

        try {

            jarray = new JSONArray( builder.toString());

        } catch (JSONException e) {

            Log.e("JSON Parser", "Error parsing data " + e.toString());

        }

 

          return jarray;

 

    }

}

 

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:

<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 :)

Up Next
    Ebook Download
    View all
    Learn
    View all