Android – Simple JSON parsing using jackson APIs


Here is a sample application which demonstrates usage of open source Jackson JSON Processor.

This sample application performs a very simple HTTP GET Request to get JSON object from http://www.kaverisoft.com/careers/assignments/android/a1.php and then uses JSONParser to parse the object.

package com.example.jsonsample;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity implements Runnable {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new Thread(this).run();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void run() {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		try {
			HttpResponse response = httpClient
					.execute(new HttpGet(
							"http://www.kaverisoft.com/careers/assignments/android/a1.php"));
			InputStream is = response.getEntity().getContent();
			JsonFactory factory = new JsonFactory();
			JsonParser jsonParser = factory.createJsonParser(is);
			JsonToken token = jsonParser.nextToken();
			ArrayList objectArray = new ArrayList();
			// Expected JSON is an array so if current token is "[" then while
			// we don't get
			// "]" we will keep parsing
			if (token == JsonToken.START_ARRAY) {
				while (token != JsonToken.END_ARRAY) {
					// Inside array there are many objects, so it has to start
					// with "{" and end with "}"
					token = jsonParser.nextToken();
					if (token == JsonToken.START_OBJECT) {
						while (token != JsonToken.END_OBJECT) {
							// Each object has a name which we will use to
							// identify the type.
							token = jsonParser.nextToken();
							if (token == JsonToken.FIELD_NAME) {
								String objectName = jsonParser.getCurrentName();
								// jsonParser.nextToken();
								if (0 == objectName.compareToIgnoreCase("BOOK")) {
									Book book = new Book();
									book.parse(jsonParser);
									objectArray.add(book);
								} else if (0 == objectName
										.compareToIgnoreCase("CAMERA")) {
									Camera camera = new Camera();
									camera.parse(jsonParser);
									objectArray.add(camera);
								} else if (0 == objectName
										.compareToIgnoreCase("MUSIC")) {
									Music music = new Music();
									music.parse(jsonParser);
									objectArray.add(music);
								}
							}
						}
					}
				}
			}
			System.out.println(objectArray);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public class Book {
		private String description;
		private String author;
		private String price;

		public void parse(JsonParser parser) throws JsonParseException,
				IOException {
			JsonToken token = parser.nextToken();
			if (token == JsonToken.START_OBJECT) {
				while (token != JsonToken.END_OBJECT) {
					token = parser.nextToken();
					if (token == JsonToken.FIELD_NAME) {
						String fieldName = parser.getCurrentName();
						// parser.nextToken();
						System.out.println(fieldName);
						if (0 == fieldName.compareToIgnoreCase("description")) {
							this.description = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("author")) {
							this.author = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("price")) {
							this.price = parser.getText();
						}
					}
				}
			}
		}

		@Override
		public String toString() {
			return "book: { author:" + author + ", description:" + description
					+ ", price:" + price + "}";
		}
	}

	public class Music {
		private String artist;
		private String album;
		private String genre;
		private String title;

		public void parse(JsonParser parser) throws JsonParseException,
				IOException {
			JsonToken token = parser.nextToken();
			if (token == JsonToken.START_OBJECT) {
				while (token != JsonToken.END_OBJECT) {
					token = parser.nextToken();
					if (token == JsonToken.FIELD_NAME) {
						String fieldName = parser.getCurrentName();
						parser.nextToken();
						System.out.println(fieldName);
						if (0 == fieldName.compareToIgnoreCase("artist")) {
							this.artist = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("album")) {
							this.album = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("genre")) {
							this.genre = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("title")) {
							this.title = parser.getText();
						}
					}
				}
			}
		}

		@Override
		public String toString() {
			return "music: { artist:" + artist + ", album:" + album
					+ ", genre:" + genre + ", title:" + title + "}";
		}
	}

	public class Camera {
		private String picture;
		private String model;
		private String price;
		private String make;

		public void parse(JsonParser parser) throws JsonParseException,
				IOException {
			JsonToken token = parser.nextToken();
			if (token == JsonToken.START_OBJECT) {
				while (token != JsonToken.END_OBJECT) {
					token = parser.nextToken();
					if (token == JsonToken.FIELD_NAME) {
						String fieldName = parser.getCurrentName();
						System.out.println(fieldName);
						parser.nextToken();
						if (0 == fieldName.compareToIgnoreCase("picture")) {
							this.picture = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("model")) {
							this.model = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("price")) {
							this.price = parser.getText();
						} else if (0 == fieldName.compareToIgnoreCase("make")) {
							this.make = parser.getText();
						}
					}
				}
			}
		}

		@Override
		public String toString() {
			return "camera: { picture:" + picture + ", model:" + model
					+ ", price:" + price + ", make:" + make + "}";
		}
	}
}

Advertisements

8 comments

    1. sorry.. can’t do your homework for you.. this code snippet demonstrate how the parsing could be done.. if you have any doubts in that then please ask.

  1. Hi. Thanks for such a nice tutorial.I ran your code and it is working perfectly.I want to use my own Json data but I am confused how to use it following your code.Could you please guide me..my Json file is “https://dl.dropboxusercontent.com/s/rhk01nqlyj5gixl/jsonparsing.txt?token_hash=AAHpfauVxJaC9Rkx_5abNtJnPFG04os7TZky1AhOuC5jEw”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s