Skip to content

Parsing JSON on Android

September 10, 2012

Hey everyone,

Now a days when people talk about transferring data through HTTP requests, two popular data formats come to mind: JSON and XML.

In earlier posts, I’ve written a little about XML (see ), but in this post I’m going to use another friendly library to show you guys a simple, efficient way to parse JSON. I’ll also talk a little about the merits of each data format, but the hope is by the end of this short post, you’ll have what you need to parse both XML and JSON.

The “library” I’m going to take advantage of is the JSON-Java library. It’s a really nice, self-contained library, which allows you to easily parse JSON. More recently, the library has even included methods that allow you to convert XML to JSON and vice versa – allowing you to better reuse your data parsers. Anyways, before reading this post, go ahead and download the library and add the source to your project. For me, I just add a new package (i.e. jwei.apps.json) and put the files in there.

Once you have that, the rest is quite simple. Recently I worked on a project where I had to make an HTTP request to get a list of clubs in NY. Each Club was simply an object that contained fields like name, address, lat/long, phone number, etc. The JSON structure of the HTTP response looked like:

[ // note that square brackets declare a json array
   { // while curly brackets declare a json object
      id: 11036,
      zip: "",
      lon: -73.9861709,
      address: "240 W 47th St,  New York, NY",
      name: "The Supper Club",
      number: "",
      url: "",
      lat: 40.7597637,
      country: "United States"
   },
   {
      id: 7034,
      zip: "10019",
      lon: -73.9863942,
      address: "251 W. 48th St,  New York, NY",
      name: "XVI",
      number: "",
      url: "",
      lat: 40.7607917,
      country: "United States"
   }
   .
   .
   .
]

To see for yourself, feel free to hit this URL:

http://djs-corner.appspot.com/getClosestClubs?lat=40.7600624&lon=-73.98558

Then, subsequently my JSON club parser looked like:

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import jwei.apps.helpers.ConnectionManager;
import jwei.apps.json.JSONArray;
import jwei.apps.json.JSONObject;
import jwei.apps.types.Club;
import jwei.apps.types.Constants;

public class JsonParser {

	private static DefaultHttpClient httpClient = ConnectionManager.getClient();

	public static List<Club> getNearestClubs(double lat, double lon) {
		// YOUR URL GOES HERE
		String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
		
		List<Club> ret = new ArrayList<Club>();
		
		HttpResponse response = null;
		HttpGet getMethod = new HttpGet(getUrl);
		try {
			response = httpClient.execute(getMethod);
			
			// CONVERT RESPONSE TO STRING
			String result = EntityUtils.toString(response.getEntity());
			
			// CONVERT RESPONSE STRING TO JSON ARRAY
			JSONArray ja = new JSONArray(result);

			// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
			int n = ja.length();
			for (int i = 0; i < n; i++) {
				// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
				JSONObject jo = ja.getJSONObject(i);
				
				// RETRIEVE EACH JSON OBJECT'S FIELDS
				long id = jo.getLong("id");
				String name = jo.getString("name");
				String address = jo.getString("address");
				String country = jo.getString("country");
				String zip = jo.getString("zip");
				double clat = jo.getDouble("lat");
				double clon = jo.getDouble("lon");
				String url = jo.getString("url");
				String number = jo.getString("number");
				
				// CONVERT DATA FIELDS TO CLUB OBJECT
				Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
				ret.add(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// RETURN LIST OF CLUBS
		return ret;
	}

}

Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

In the first method, we pass in a String which has JSON format. The constructor of JSONArray expects a String that has valid JSON array formatting and parses it accordingly – throwing a JSONException otherwise. Once we have our JSON array, it works similarly to a vector (ArrayList) and we can pass it an index and retrieve a single JSONObject. For each JSONObject, we can then retrieve various fields by type (i.e. getLong, getDouble, getString, etc). Pretty simple no?

As mentioned before, to allow for better re-usability of data parsers, the writers of JSON-Java extended the library’s functionality to include XML conversion, which is simply:

String xml = ""; // YOUR XML STRING
JSONObject jo = XML.toJSONObject(xml);
String name = jo.getString("name");
...

Thus, if we wanted to ensure maximum compatibility, we could have extended our parser to look like:


public class JsonParser {

	private static DefaultHttpClient httpClient = ConnectionManager.getClient();

	public static List<Club> getNearestClubs(double lat, double lon, String format) {
		// YOUR URL GOES HERE - OFTEN API REQUESTS WILL HAVE A FORMAT PARAM
		String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f&format=%s", lat, lon, format);
		
		List<Club> ret = new ArrayList<Club>();
		
		HttpResponse response = null;
		HttpGet getMethod = new HttpGet(getUrl);
		try {
			response = httpClient.execute(getMethod);
			
			// CONVERT RESPONSE TO STRING
			String result = EntityUtils.toString(response.getEntity());
			
			// CONVERT RESPONSE STRING TO JSON ARRAY
			JSONArray ja;
			if(format.equalsIgnoreCase("xml")) {
				JSONObject xjo = XML.toJSONObject(result);
				ja = xjo.getJSONArray("clubs");
			} else if (format.equalsIgnoreCase("json")) {
				ja = new JSONArray(result);
			}

			// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
			...
		} catch (Exception e) {
			e.printStackTrace();
		}

		// RETURN LIST OF CLUBS
		return ret;
	}

}

And voila!

Now, as for a brief discussion on JSON vs. XML, I’ll note three points:

1) Performance – in terms of performance, JSON is the better option. This is true for both the actual transferring of your data, and also for the parsing of the data. This is due to the lower overhead needed for JSON formatting, which doesn’t require the rigid tree/node structure of XML.

2) Readability – this is a more subjective point and I’ve seen arguments for both sides. I personally think XML is the cleaner format for reading, but most browsers now a days (i.e. Chrome, Firefox) have JSON and XML display built in and both are nicely laid out. However, I will mention that for more “complex” data structures, XML tends to display it in a more intuitive fashion, which leads me to my third point.

3) Complexity – while JSON is designed for quick and lean data structures, XML is built to handle data structures of varying complexity and depth. Consider a data structure that has fields which are several layers deep (i.e. a University object which has a list of Class objects which each have a list of Student objects which each have a list of …). When this is the case, it can quickly become a parsing headache when you’re wading through JSONArray after JSONArray trying to access the correct JSONObject. Here, having an XML parser, especially one that is equipped with tree traversing languages like XPATH, can be an extremely powerful tool for pinpointing the precise nodes you want.

And so I’ll end the post with that. Hope this was comprehensive and helpful!

As always – happy coding.

- jwei

About these ads
9 Comments leave one →
  1. Bijesh permalink
    September 10, 2012 9:58 pm

    gud one i will try some samples with JSON…

  2. September 11, 2012 8:40 am

    Yes I have had extensive JSON parsing with Android and this solution is something similar to what I have used before. The JSON parser is easier to use and faster than XML and much simpler.

    • September 11, 2012 9:12 am

      Hey grndvl1,

      Yup agreed. I’ve seen several tutorials out there which attempt to build their own JSON parsers, and though it’s certainly not a hard task to do, I’ve just found that the JSON-Java library makes things super simple and clean.

      - jwei

  3. alex permalink
    September 17, 2012 3:03 pm

    Thanks for the article.
    I’d suggest to check out DroidParts (http://droidparts.org), namely:
    - RESTClient2 that has a single method for GETting JSON arays.
    - JSONSerializer that’s built on top of JSON-Java.

  4. September 18, 2012 2:40 am

    I have used the Spring Android project to parse JSON in the past and found it very easy to use:

    By passing the class type to the RestTemplate, it will return the java version of the JSON to you. For example:
    ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Event[].class);

    You can see the full example here:
    http://static.springsource.org/spring-android/docs/1.0.x/reference/html/rest-template.html#d4e401

    • September 18, 2012 11:52 am

      Hey Stephen,

      Thanks for this! Haven’t seen this library before – looks convenient though I’m a little scared that there’s almost too much abstraction here which could potentially make it hard to debug? Not sure – just my gut instinct though I’m sure you could speak more knowledgeably about this library. In any case thanks again!

      - jwei

      • September 18, 2012 12:01 pm

        I have used on a few projects without any issue. It means I dont have to worry about parsing or converting each JSON field to a Java variable, I just supply the annotated Java class and it gets populated.

        ….just my two cents anyway.

  5. thumbar keyur permalink
    November 25, 2012 9:50 pm

    hi
    can u plz tell me is thier any use of database in json and where to run json file. i working with eclipse and net beans .

    • November 27, 2012 7:40 am

      Hi Thumbar,

      What do you mean by “database in JSON” and “where to run JSON file”? JSON is simply a human-readable data format for transmitting data. I’m not sure what the notion of “running” a JSON file means.

      - jwei

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

Follow

Get every new post delivered to your Inbox.

Join 845 other followers

%d bloggers like this: