This tutorial is about json parsing in android. We will be using AsyncTask to implement JSON parser simple example. If you want to build an app which will be having its back end on some server or if you are trying to parse the data from any URL in form of JSON object, then this tutorial can be useful.

Note: At the end of this tutorial you can find complete code for json parser. If you only want code then you can skip the step by step explanation.

Step By Step Explanation

Implementing the JSON parser class

A program that needs to read data from some source needs an inputstreamreader. InputStream receives the data as a byte-stream from the source. In our case the source is URL at which JSON is present.

static InputStream is = null;
static JSONObject jobj = null;
static String json = "";

Note: jobj will be holding the JSON object which we get from url.

Code to receive JSON from URL

  1. We can retrieve and send data via HTTPClient.
  2.  httppost tells that our requested method is post and HTTPResponse stores the response of the request locally.
  3. “url” is the link where the JSON object is present on the webpage.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse httpresponse = httpclient.execute(httppost);

httpentity helps us to extract the data from response and we use inputstream to get the content of the data.

HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();

Transform the received data from URL

json Data present at URL is given below. We get this data as a stream of bytes using InputStream. So we need to transform this data to re-make the JSON object .

{
   "firstname": "Rajat",
   "lastname": "Ghai"
}

BufferedReader works on text, while InputStream work on bytes. We use InputStreamReader to convert byte-stream into character-stream, so that we can pass it into constructor of BufferedReader. BuffereReader will be holding our character-stream.

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

  • We are converting character stream into a String object. Then we will convert this string object to re-create json object.
  • Use StringBuilder to build a String object.
  • readline() method is used to read one line at a time from BufferedReader and append it into string.
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}

Close the InputStream and convert the string builder data to an actual String.  json is a string object and it is passed into constructor of JSONObject to create a json object.

is.close();
json = sb.toString();
jobj = new JSONObject(json);
// we will return json object so that it can be further processed
return jobj;

complete code of  JSONParser class.

package com.example.expensesharing;

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

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

public class JSONParser {

	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = "";
	public JSONParser(){

	}
	public JSONObject makeHttpRequest(String url){
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			try {
				HttpResponse httpresponse = httpclient.execute(httppost);
				HttpEntity httpentity = httpresponse.getEntity();
				is = httpentity.getContent();

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				try {
					while((line = reader.readLine())!=null){
						sb.append(line+"\n");	

					}
					is.close();
					json = sb.toString();
					try {
						jobj = new JSONObject(json);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		return jobj;

	}

}

 

Now let us Implement our Main activity file.

Importing packages

To handle all the exceptions related to json parsing, we import JSONException and to create instance of json and to access all the methods we need to import JSONObject.

AsyncTask is used to implement background thread, so that we will be doing all the blocking operations in our separate thread.

import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
  •  ”JSONParser” is a user defined class which will be implemented by us.
  • “tv” will display the string which we get from JSON object.
  • “jobj” is a JSON object and it can access methods which are required in json handling.
JSONParser jsonparser = new JSONParser();
TextView tv;
String ab;
JSONObject jobj = null;

Execute our AsynchTask, so that all the networking operation can be implemented in main thread.

new retrievedata().execute();

First, we create retrievedata class which is an AsynchTask i.e it will run in background thread.

Reason for using another thread.

Each android application runs in its own process and in one single thread which is called Main thread or UI thread. Any operation which is heavy or which will block our main thread, should be implemented in a separate thread. For example Networking is a blocking operation. Here we are receiving data from internet that’s why we are implementing in background thread. I hope things are getting much clear now. Is it ?

AsynchTask helps us to implement a background thread.  It has few methods,which you can override. “doInBackground” is the method which will be having the main code. “onPostExecute” will contain stuff to update the data on TextView, which we have received from internet.

@Override
protected String doInBackground(String... arg0){
}
@Override
protected void onPostExecute(String msg) {
}

jsonparser is an instance of JSONParser class, which we have implemented. It is having makeHttpRequest() method, in which url is passed as a parameter and this method will return a JSON object.

class retrievedata extends AsyncTask<String,String,String>{
// a function to get JSON from url
 jobj = jsonparser.makeHttpRequest("http://www.yourwebsite.com/at/json.php");

protected String doInBackground(String... arg0) {
//string object   
   ab = jobj.getString("key");			
   return ab;
}
protected void onPostExecute(String ab){
	tv.setText(ab);
}
  • JSON object is simply a key -> value pair.
  •  getString() method is used to get the value of “key”.
  • Now, string will be passed to onPostExecute() method and we will set the value of TextView.

Now let us see the complete code of json parsing in android. You can direclty edit the URL from which you want to parse the json and then you can easily manipulate the data.

Complete code of our Main activity file.

package com.example.expensesharing;

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class Main extends Activity {
	JSONParser jsonparser = new JSONParser();
	TextView tv;
	String ab;
	JSONObject jobj = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.textView1);
		new retrievedata().execute();

	}

	@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;
	}
	class retrievedata extends AsyncTask<String,String,String>{

		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			jobj = jsonparser.makeHttpRequest("http://www.yourwebsite.com/at/json.php");

			// check your log for json response
			Log.d("Login attempt", jobj.toString());

			try {
				ab = jobj.getString("key");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return ab;
		}
		protected void onPostExecute(String ab){

			tv.setText(ab);
		}

	}

}

 

Hope you have enjoyed this simple tutorial. Let me know if you have any errors or suggestions.