Home > Uncategorized > Android: Why To Use JSON And How To Use It

Android: Why To Use JSON And How To Use It

Herewith you will learn how to use JSON in Android to fetch informaiton from server, what is JSON Object, JSONArray. It is a pretty common task in smartphone application development to query a website for some information, do a bit of processing, and present it to the user in a different form. There are two different main ways of going about this:

1.) Just download a whole webpage and use an HTML or XML parser to try and extract the information which you want.
2.) Some websites have API’s which allow queries that instead of returning webpages, return XML, JSON, or some other way of presenting data.

Clearly, option 2 (if available) makes a lot more sense. Instead of downloading a large webpage (wasting data), parsing the entire thing (wasting battery), and then trying to analyze it (wasting your time going through often improperly written HTML), you can download much smaller, easier to manage text which conforms to XML, JSON, or whatever it is that the API provides. (I will be posting another tutorial about option 1 soon).

You might wonder why you would want to use JSON instead of XML for your smartphone application. After all, XML has been a much-ballyhooed technology buzzword for many years. There is, however, a good (and simple) reason. XML is (usually) bigger. The closing tags in XML do not exist in JSON, and therefore save you a few bytes for each tag that you don’t need. JSON can generally express the same data using fewer characters, thus saving the phone from having to transfer more data every time there is a query to a website. This makes JSON a natural choice for quick and efficient website querying (for websites which offer it).

One such website is http://www.archive.org. Among many other things, archive.org allows people to upload recordings from concerts for other people to download for free. It’s pretty awesome. They also have an API which allows you to query their system which will return results in XML, JSON, or a variety of other formats.

I am currently writing an application for browsing archive.org from your phone to find shows and then either download or stream the tracks. I’ll show you how I do the first part (finding shows) using JSON and just a few lines of code.

First, you need your JSON query. I am going to query archive.org for “Lotus,” asking for a JSON result containing 10 items with their respective date, format, identifier, mediatype, and title. According to the archive.org search API, my query should look like this:

String archiveQuery = "http://www.archive.org/advancedsearch.php?q=Lotus&fl[]=date&fl[]=format&fl[]=identifier&fl[]=mediatype&fl[]=title&sort[]=createdate+desc&sort[]=&sort[]=&rows=10&page=1&output=json&callback=callback&save=yes";

Now that we have our query, we simly open an HTTP connection using the query, grab an input stream of bytes and turn it into a JSON object. On a side note, notice that I am using a BufferedInputStream because its read() call can grab many bytes at once and put them into an internal buffer. A regular InputStream grabs one byte per read() so it has to pester the OS more and is slower and wastes more processing power (which in turn wastes battery life).

InputStream in = null;String queryResult = "";try { URL url = new URL(archiveQuery); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setAllowUserInteraction(false); httpConn.connect(); in = httpConn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; int bufSize = 512; byte[] buffer = new byte[bufSize]; while(true){ read = bis.read(buffer); if(read==-1){ break; } baf.append(buffer, 0, read); } queryResult = new String(baf.toByteArray());} catch (MalformedURLException e) { // DEBUG Log.e("DEBUG: ", e.toString());} catch (IOException e) { // DEBUG Log.e("DEBUG: ", e.toString());}

At this point, our JSON response is stored in the String queryResult. It looks kind of like this:

callback({ "responseHeader": {... *snip* ... }, "response": { "numFound": 1496, "start": 0, "docs": [{ "mediatype": "audio", "title": "The Disco Biscuits At Starscape 2010", "identifier": "TheDiscoBiscuitsAtStarscape2010", "format": ["Metadata", "Ogg Vorbis", "VBR MP3"] }, { "title": "Lotus Live at Bonnaroo Music & Arts Festival on 2010-06-10", "mediatype": "etree", "date": "2010-06-10T00:00:00Z", "identifier": "Lotus2010-06-10TheOtherStageBonnarooMusicArtsFestivalManchester", "format": ["Checksums", "Flac", "Flac FingerPrint", "Metadata", "Ogg Vorbis", "Text", "VBR MP3"] }, { "title": "Lotus Live at Mr. Smalls Theatre on 2006-02-17", "mediatype": "etree", "date": "2006-02-17T00:00:00Z", "identifier": "lotus2006-02-17.matrix", "format": ["64Kbps M3U", "64Kbps MP3", "64Kbps MP3 ZIP", "Checksums", "Flac", "Flac FingerPrint", "Metadata", "Ogg Vorbis", "Text", "VBR M3U", "VBR MP3", "VBR ZIP"] }, {... *snip* ...

We see that the information we want is stored in an array whose key is “docs” and is contained in an item called “response”. We can grab this information VERY easily using the JSONObject class provided by Android as shown below:

JSONObject jObject;try { jObject = new JSONObject(queryResult.replace("callback(", "")).getJSONObject("response"); JSONArray docsArray = jObject.getJSONArray("docs"); for (int i = 0; i < 10; i++) { if (docsArray.getJSONObject(i).optString("mediatype").equals("etree")) { String title = docsArray.getJSONObject(i).optString("title"); String identifier = docsArray.getJSONObject(i).optString("identifier"); String date = docsArray.getJSONObject(i).optString("date"); System.out.println(title + " " + identifier + " " + date); } }} catch (JSONException e) { // DEBUG Log.e("DEBUG: ", JSONString); Log.e("DEBUG: ", e.toString());}

The first thing that I do is create a JSONObject from “queryResult”, which is the JSON response from archive.org. Note that I remove “callback(” from the JSON string because, even though archive.org returns it, it should not actually be part of the JSON string (I realized this when I was catching JSONException errors).

After that, we are ready to do some JSON parsing. Since this is just a tutorial, I hardcode “10” into the for loop because I requested 10 items. This would be a bad idea in production code (if you don’t know why you are a huge noob and should not be writing production code). I only want items whose mediatype is “etree”, and for each of these items I print the title, identifier, and date.

Voila, you now know how to use JSON in Android.

Categories: Uncategorized
  1. manju
    January 30, 2012 at 8:07 pm

    nice article

  2. dhana
    February 26, 2013 at 7:51 am


  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: