JSON Parsing – Android

Home / Android / JSON Parsing – Android

The last post XML Parsing using SAXParser was about parsing a web service providing XML. In this post we are going to parse JSON available at http://www.pcsalt.com/postservice/?format=json. The JSON available at the link may seem messy, for the formatted view of JSON JSONLint.

In order to parse JSON, at first we should examine the JSON and determine what is it we need to parse.

Demo JSON abstract

{
    "posts": [
        {
            "post": {
                "post_title": "Add EditText Programmatically - Android",
                "guid": "http://www.pcsalt.com/?p=249",
                "post_date": "2013-01-26 01:05:35"
            }
        },
        {
            "post": {
                "post_title": "Android SQLite Database - Part 1/2",
                "guid": "http://www.pcsalt.com/?p=442",
                "post_date": "2013-04-18 23:48:59"
            }
        }
    ]
}

In this JSON posts is a JSONArray which contains an array of JSONObject post. And, JSONObject post contains three Strings, namely, post_title, guid, and post_date. In short, [ ] denotes array of elements and { } denotes JSONObject. You can visit www.json.org for more description about JSON elements.




For this tutorial we have a simple layout with a TextView inside a ScrollView, and the parsed information is displayed in a TextView.

activity_main.xml


NOTE: It is advisable to use ListView with BaseAdapter to display such type of parsed information.

In order to parse JSON we need to get to the URL and get the JSON in our application. For this purpose, we would need a helper class to do the same.

JSONHelper.java

package pcsalt.example.jsonparsing;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONHelper {
	String URL_MAIN = "http://pcsalt.com/postservice/?format=json";
	static InputStream is = null;
	static JSONObject mJsonObject = null;
	static String json = "";
	String TAG = getClass().getSimpleName();

	public JSONObject getJSONFromUrl() {
		try {
			// Create default http client to open URL
			DefaultHttpClient mDefaultHttpClient = new DefaultHttpClient();
			HttpPost mHttpPost = new HttpPost(URL_MAIN);

			// Execute the Post request and get the response from server
			HttpResponse mHttpResponse = mDefaultHttpClient.execute(mHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			// Get the response into the InputStream
			is = mHttpEntity.getContent();
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
			e.printStackTrace();
		}

		try {
			// Read the response in InputStream and build local JSON in a String
			BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder builder = new StringBuilder();
			String line = null;
			while ((line = mBufferedReader.readLine()) != null) {
				builder.append(line + "\n");
			}
			is.close();
			json = builder.toString();
		} catch (Exception e) {
			Log.e(TAG, "Exception: " + e.getMessage());
		}

		try {
			// Convert the JSON String from InputStream to a JSONObject
			mJsonObject = new JSONObject(json);
		} catch (JSONException e) {
			Log.e(TAG, "Exception: " + e.getMessage());
		}

		return mJsonObject;
	}
}

Now, we can get the JSON from URL using this class. But, we need to keep those values from JSONObjects and JSONArray. For this purpose we need to have a holder class named PostValue. This is getter/setter class to preserve the values from JSON.

PostValue.java

package pcsalt.example.jsonparsing;

public class PostValue {
	String title, guid, date;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getGuid() {
		return guid;
	}

	public void setGuid(String guid) {
		this.guid = guid;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}
}

Since, we are going to download the JSON from internet, that’s why we are going to use AsyncTask for this purpose.

MainActivity.java

package pcsalt.example.jsonparsing;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

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

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    String TAG = getClass().getSimpleName();
    JSONObject mJsonObject;
    ListView lvPcsPost;
    PostValue postValue;
    ArrayList postList = new ArrayList();

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

        lvPcsPost = (ListView) findViewById(R.id.lvPcsPost);
        lvPcsPost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                if (postList != null && postList.size() > 0) {
                    Intent intentShowPost = new Intent(Intent.ACTION_VIEW, Uri.parse(postList.get(position).getGuid()));
                    startActivity(intentShowPost);
                }
            }
        });
        new JSONAsync().execute();
    }

    void parse() {
        JSONHelper mJsonHelper = new JSONHelper();

        mJsonObject = mJsonHelper.getJSONFromUrl();

        try {
            JSONArray postsArray = mJsonObject.getJSONArray("posts");

            for (int i = 0; i < postsArray.length(); i++) {
                JSONObject posts = postsArray.getJSONObject(i);
                JSONObject post = posts.getJSONObject("post");

                postValue = new PostValue();

                String title = post.getString("post_title");
                String guid = post.getString("guid");
                String date = post.getString("post_date");

                postValue.setTitle(title);
                postValue.setGuid(guid);
                postValue.setDate(date);
                postList.add(postValue);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class JSONAsync extends AsyncTask {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(MainActivity.this, "PCSalt", "Loading posts for PCSalt.com ...", true, false);
        }

        @Override
        protected Void doInBackground(Void... params) {
            parse();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            PostBaseAdapter postBaseAdapter = new PostBaseAdapter(MainActivity.this, postList);
            lvPcsPost.setAdapter(postBaseAdapter);
            pd.dismiss();
        }
    }

}

In MainActivity we are parsing the JSON using PostValue and JSONHelper classes and setting the acquired values in the layout for display.

AndroidManifest.xml




    
    

    
        
            
                

                
            
        
    


build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "pcsalt.example.jsonparsing"
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Download Source:

JSONParsing - GitHub